<template>
  <div class="app-container order-edit pb-160" v-cloak>
    <div class="shop-container">
      <h3>商品信息</h3>
      <span
        v-if="
          ruleForm.replaceDeliveryTime == 1"
        class="timecolor"
        style="width: 86%; font-size: 20px"
        >更换配送时间</span
      >
      <div v-loading="detailLoading" class="minh-200">
        <goodsItem v-for="(detail, index) in shoplist.filter(item => item.gift != 1)" :key="index" :detail="detail" :ruleForm="ruleForm" :categoriesList="getCategoriesList"></goodsItem>
        <div v-if="shoplist.some(item => item.gift == 1)">
          <h3>赠送商品信息</h3>
          <goodsItem v-for="(detail, index) in shoplist.filter(item => item.gift == 1)" :key="index" :detail="detail" :ruleForm="ruleForm" :categoriesList="getCategoriesList"></goodsItem>
        </div>
      </div>
      <div v-if="canEditGoods" class="EditCake">
        <el-button type="primary" @click="openEditCake">编辑商品</el-button>
      </div>
    </div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm"
    >
      <div class="payment-container">
        <h3>支付</h3>
        <el-form-item label="在线支付" prop="sumPrice">
          <el-input
            v-model.trim="ruleForm.sumPrice"
            maxlength="9"
            oninput="value=value.replace(/[^\d.]/g,'')"
            placeholder="请填写价格"
            clearable
            size="medium"
            :disabled="!canEditPay"
          ></el-input>
          <span style="margin-left: 15px">元</span>
        </el-form-item>
      </div>
      <div class="channel-container">
        <h3>渠道</h3>
        <el-form-item label="渠道类别" prop="channelType">
          <el-select
            v-model.trim="ruleForm.channelType"
            size="medium"
            filterable
            placeholder="渠道类别"
            :disabled="!canEditChannel"
          >
            <el-option
              v-for="(channelitem, channel) in channelTypellist"
              :key="channel"
              :label="channelitem.channelName"
              :value="channelitem.channelKey"
            >
              <span
                :data-id="channelitem.id"
                :data-channelName="channelitem.channelKey"
                style="
                  display: block;
                  width: 100%;
                  padding: 0 20px;
                  margin-left: -20px;
                "
                @click="getchannelTypeId($event)"
                >{{ channelitem.channelName }}</span
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道" prop="channel">
          <el-select
            v-model.trim="ruleForm.channelName"
            @change="getChannel"
            size="medium"
            filterable
            placeholder="渠道"
            :disabled="!canEditChannel"
          >
            <el-option
              v-for="(channelitem, channel) in channerllist"
              :key="channel"
              :label="channelitem.channelName"
              :value="{
                value: channelitem.channelKey,
                label: channelitem.channelName,
              }"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="detail-container">
        <h3>订单信息</h3>
        <el-form-item label="后台单号" prop="xmbzNo">
          <el-col>{{ ruleForm.xmbzNo }}</el-col>
        </el-form-item>
        <el-form-item label="平台单号">
          <!-- <el-col>{{ruleForm.platformOrderId}}</el-col> -->
          <el-input
            v-model.trim="ruleForm.platformOrderId"
            clearable
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="收货人" prop="receiverName">
          <el-input
            v-model.trim="ruleForm.receiverName"
            maxlength="10"
            onkeyup="value=value.replace(/\s+/g, '')"
            onafterpaste="value=value.replace(/\s+/g, '')"
            show-word-limit
            clearable
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="收货人电话" prop="receiverPhone">
          <el-input
            type="text"
            v-model.trim="ruleForm.receiverPhone"
            maxlength="50"
            @input="filterPhone"
            show-word-limit
            autosize
            clearable
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="下单电话" prop="bookerPhone">
          <el-input
            type="text"
            v-model.trim="ruleForm.bookerPhone"
            maxlength="50"
            show-word-limit
            autosize
            clearable
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="订制商品" v-if="showCustomMade" prop="diyCakeName">
          <diyCakeInfo ref="diyCakeInfo" @diyChange="handleDiyChange"></diyCakeInfo>
        </el-form-item>
        <el-form-item label="客户备注" prop="customerNotes">
          <el-input
            class="orderspecial"
            v-model="ruleForm.customerNotes"
            type="textarea"
            maxlength="50"
            @input="filterSpace('customerNotes')"
            show-word-limit
            autosize
            clearable
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="生产备注" prop="productionNotes">
          <el-input
            v-model="ruleForm.productionNotes"
            type="textarea"
            maxlength="100"
            @input="filterSpace('productionNotes')"
            show-word-limit
            autosize
            clearable
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="配送备注" prop="deliveryNotes">
          <el-input
            v-model="ruleForm.deliveryNotes"
            onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}"
            type="textarea"
            maxlength="200"
            @input="filterSpace('deliveryNotes')"
            show-word-limit
            autosize
            clearable
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="客服备注" prop="customerServiceNotes">
          <div slot="label" class="">
            <div class="lh-20">客服备注</div>
            <div class="lh-20 c-red fw-bold">（仅客服使用）</div>
          </div>
          <el-input
            v-model="ruleForm.customerServiceNotes"
            type="textarea"
            maxlength="200"
            @input="filterSpace('customerServiceNotes')"
            show-word-limit
            autosize
            clearable
            size="medium"
          ></el-input>
        </el-form-item>
        <el-form-item label="平台门店" prop="merchantName">
          <span>
            {{ ruleForm.merchantName }}
          </span>
        </el-form-item>
        <el-form-item label="门店信息">
          <span class="pl-20">
            {{ ruleForm.storeInfo }}
          </span>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.groupBuyQRCode ? true : false"
          label="团购二维码"
          prop="groupBuyQRCode"
        >
          <img
            :src="ruleForm.groupBuyQRCode"
            alt=""
            style="width: 450px; height: 450px"
          />
        </el-form-item>
      </div>
      <div class="detail-container" v-if="ruleForm.addedServiceVO && ruleForm.addedServiceVO.length">
        <h3>增值服务信息</h3>
        <div class="ml-200 d-f">
          <el-card v-for="(item, i) in ruleForm.addedServiceVO" :key="i" class="w-300 mr-20 mb-20 d-ib">
            <div slot="header" class="clearfix">
              <span>{{ item.typeName }}</span>
            </div>
            <div class="lh-32">
              <span>是否满足服务：</span>
              <el-tag class="" :type="item.pass == '1' ? 'success' : 'danger'">{{ item.pass == '1' ? '满足' : '不满足' }}</el-tag>
            </div>
            <div class="lh-32">
              <span>反馈原因/备注信息：</span>
              <span class="">{{ item.passValue }}</span>
            </div>
          </el-card>
        </div>
      </div>
      <div class="detail-container" v-if="consultHappyOrderList && consultHappyOrderList.length">
        <h3>咨询快乐工单结果</h3>
        <div class="ml-200 d-f">
          <el-card v-for="(item, i) in consultHappyOrderList" :key="i" class="w-300 mr-20 mb-20 d-ib">
            <el-tag v-if="consultHappyDisposeType[item.disposeState]" :type="consultHappyDisposeType[item.disposeState].type">{{ consultHappyDisposeType[item.disposeState].label }}</el-tag>
            <div class="lh-40">咨询内容：{{ item.content }}</div>
            <div class="lh-40">咨询结果：{{ item.resultContent }}</div>
          </el-card>
        </div>
      </div>
      <div class="address-container">
        <h3>配送地址和时间</h3>
        <el-form-item
          label="配送时间"
          prop="deliveryStartTime"
          class="deliveryTimeStyle"
        >
          <el-col v-if="(ruleForm.deliveryStartTime && ruleForm.deliveryEndTime)">客户备注时间：
            {{ ruleForm.deliveryStartTime.slice(5, 16) }}~{{ ruleForm.deliveryEndTime.slice(11, 16) }}</el-col>
          <div style="display: inline-flex; margin-left: -10px">
            <el-date-picker
              type="date"
              size="medium"
              :placeholder="getdelOrderStartTime"
              v-model="getdeliveryStartTime"
              :picker-options="pickerOptionsStart"
              :clearable="false"
              value-format="yyyy-MM-dd "
              :disabled="
                orderStatus == 8 ||
                !permissionList.detail_edit_time
              "
              format="yyyy-MM-dd "
              style="width: 170px; margin: 0 0 0 10px"
            ></el-date-picker>
            <div class="line" :span="1" style="margin: 0 10px">-</div>
            <selecttime
              ref="getdeliveryTime"
              v-bind:disable="!permissionList.detail_edit_time"
              v-bind:deliveryTime="getdeliveryStartTime"
              v-bind:OrderStartTime="ruleForm.deliveryStartTime"
              v-bind:OrderEndTime="ruleForm.deliveryEndTime"
              style="width: 170px; margin: 0"
            ></selecttime>
          </div>
        </el-form-item>
        <div class="el-form-item title-timeShow">
          <p
            v-for="(item, index) in this.wareHouseTime.warehouseDeliveryTimes"
            :key="index"
            class="changeColor"
          >
            {{ item.deliveryStartTime.substr(0, 5) }}-{{
              item.deliveryEndTime.substr(0, 5)
            }}
            需提前{{ item.orderAdvanceTime }}分钟下单，
            {{
              changeDeliveryStartTime(
                item.deliveryStartTime,
                item.deliveryEndTime,
                item.orderAdvanceTime
              )
            }}
          </p>
          <p
            v-for="(item, index) in this.wareHouseTime.warehouseCloseTimes"
            :key="index"
          >
            关闭接单时间:{{
              changeDeliveryEndTime(item.closeStartTime, item.closeEndTime)
            }}
          </p>
        </div>
        <el-form-item label="仓库" class="house-style">
          <el-select
            v-model="deptName"
            placeholder="城市"
            size="small"
            style="width: 130px"
            @change="cityclick"
          >
            <el-option
              v-for="(house, citykey) in cityselect"
              :key="citykey"
              :label="house.deptName"
              :value="{ value: house.id, label: house.deptName }"
            ></el-option>
          </el-select>
          <el-select
            v-model="ruleForm.mainWarehouse"
            placeholder="仓库"
            size="medium"
            style="width: 280px; margin-left: 5px"
          >
            <el-option
              v-for="(house, ware) in citylist"
              :key="ware"
              :label="house.deptName"
              :value="house.deptName"
            >
              <span
                :data-id="house.id"
                style="
                  display: block;
                  width: 100%;
                  padding: 0 20px;
                  margin-left: -20px;
                "
                @click="wareclick($event)"
                >{{ house.deptName }}</span
              >
            </el-option>
          </el-select>
          <el-select
            v-model="ruleForm.branchWarehouse"
            placeholder="仓库"
            size="medium"
            style="width: 200px; margin-left: 5px"
          >
            <el-option
              v-for="(house, ware) in abbrlist"
              :key="ware"
              :label="house.name"
              :value="house.name"
            >
              <span
                :data-warehouseId="house.id"
                @click="getwarehouseId(house.id)"
                style="
                  display: inline-block;
                  width: 200px;
                  padding: 0 20px;
                  margin-left: -20px;
                "
                >{{ house.name }}</span
              >
            </el-option>
          </el-select>
        </el-form-item>
        <div>
          <el-form-item label="定位" class="getAddress deletePadding" v-clickoutside="onClickSearchOutside">
            <el-input
              type="textarea"
              id="getDetail"
              ref="search"
              placeholder="请输入地址"
              @keyup.up.native="selectTopItem()"
              @keyup.down.native="selectBottomItem()"
              @keydown.enter.native="getlnglat(currentIndex)"
              v-model="receiverDetailAddress"
              clearable
              size="medium"
              @focus="SearchAddress"
              @input="SearchAddress"
              maxlength="54"
              onkeyup="value=value.replace(/\s+/g, '')"
              onafterpaste="value=value.replace(/\s+/g, '')"
              show-word-limit
              autosize
              style="sty: 480px"
            ></el-input>
            <div class="adressDetailDivCopy" id="mapDiv">
              <ul
                v-show="addressFlagcopy"
                id="mapDiv"
                class="adressDetail"
              >
                <li
                  id="mapDiv"
                  v-for="(addressitem, index) in addressList.slice(
                    (currentPage - 1) * pagesize,
                    currentPage * pagesize
                  )"
                  :key="index"
                  :class="currentIndex == index ? 'addressActive' : ''"
                  @click="getlnglat(index)"
                  @mouseover="changeColor(index)"
                  @mouseout="loseColor(index)"
                >
                  <p id="mapDiv" class="el-icon-location-information">
                    {{ addressitem.name }}
                  </p>
                  <p id="mapDiv" class="el-icon-location-information">
                    地址：<span
                      v-if="addressitem.address.length > 0 ? true : false"
                      >{{ addressitem.address }}</span
                    >
                  </p>
                  <p id="mapDiv" class="el-icon-location-information">
                    城市：<span
                      v-if="addressitem.district !== '' ? true : false"
                      >{{ addressitem.district }}</span
                    >
                  </p>
                </li>
                <el-pagination
                  id="mapDiv"
                  background
                  :current-page.sync="currentPage"
                  layout="prev, pager, next, sizes, total, jumper"
                  :page-sizes="[5, 10, 15, 20]"
                  :page-size.sync="pagesize"
                  :total="addressList.length"
                  @current-change="handleCurrentChange"
                  @size-change="handleSizeChange"
                  style="margin-top: 5px 0"
                >
                </el-pagination>
              </ul>
            </div>
          </el-form-item>
          <el-form-item label="地址" prop="receiverAddress">
            <el-input
              id="getDetailAddress"
              type="textarea"
              v-model="ruleForm.receiverAddress"
              onkeyup="value=value.replace(/\s+/g, '')"
              onafterpaste="value=value.replace(/\s+/g, '')"
              placeholder="详细地址"
              maxlength="54"
              clearable
              show-word-limit
              autosize
              size="medium"
              class="deletePadding"
              style="width: 480px"
            ></el-input>
          </el-form-item>
          <el-form-item label="坐标" prop="longAndLat">
            <el-input
              v-model.trim="ruleForm.longAndLat"
              placeholder="115.781085,36.111883"
              size="medium"
              style="width: 480px"
            ></el-input>
          </el-form-item>
          <XmMap ref="xmMap" style="width: 90%;height: 800px;"></XmMap>
          <el-col class="submit-order">
            <el-button
              v-if="permissionList.detail_preservation"
              size="medium"
              type="warning"
              @click="isConfirmCancelOrder ? null : preservation('ruleForm')"
              style="margin-left: 20px"
              >保存信息</el-button
            >
            <el-button
              v-if="
                ruleForm.refundMark == '平台退款中' &&
                permissionList.detail_platformrefund
              "
              type="warning"
              plain
              @click="PlaRefund"
              >拒绝平台退款</el-button
            >
            <el-button
              v-if="RefundNoReFlag && permissionList.detail_returngoods"
              type="danger"
              plain
              size="medium"
              @click="RefundNoRe"
              style="margin-left: 20px"
              >退款不退货</el-button
            >
            <el-button
              v-if="reminderOrderFlag && permissionList.detail_reminders"
              size="medium"
              @click="reminderOpen"
              style="margin-left: 20px"
              >催单</el-button
            >
            <el-button
              v-if="frmLossOrderFlag && permissionList.detail_provision"
              size="medium"
              @click="frmLossOpen"
              style="margin-left: 20px"
              >备款</el-button
            >
            <el-button
              v-if="complainOrderFlag && permissionList.detail_complaint"
              size="medium"
              @click="complainOpen"
              style="margin-left: 20px"
              >投诉</el-button
            >
            <el-button
              v-if="returnOrderFlag && permissionList.detail_unsubscribe"
              type="danger"
              size="medium"
              @click="returnGoodsOpen"
              style="margin-left: 20px"
              >退订</el-button
            >
            <el-button
              v-if="refundMoneyFlag && permissionList.detail_refund"
              type="danger"
              size="medium"
              @click="refundOpen"
              style="margin-left: 20px"
              >退款</el-button
            >
            <el-button
              v-if="permissionList.detil_clone_order"
              style="margin-left: 20px"
              type="danger"
              size="medium"
              @click="copeOrder"
              >复制订单</el-button
            >
            <el-button
              v-if="orderFlag"
              type="success"
              plain
              size="medium"
              @click="recoverOpen($event)"
              style="margin-left: 20px"
              >恢复订单</el-button
            >
            <el-button
              type="danger"
              size="medium"
              @click="labelOpen()"
              style="margin-left: 20px"
              >打标</el-button
            >
            <el-button
              v-if="transToCusBtnShow"
              type="danger"
              size="medium"
              @click="transToCustomerS()"
              style="margin-left: 20px"
              >{{
                ruleForm.staffForward === "客服转接" ? "取消退款挽留" : "退款挽留"
              }}</el-button
            >
            <el-button
              size="medium"
              @click="handleConsultHappy()"
              class="ml-20"
              >咨询快乐工单</el-button
            >
            <el-button
              size="medium"
              @click="$refs.orderLogDialog.show({orderId: ruleForm.id})"
              class="ml-20"
              >日志</el-button>
            <el-button
              v-if="
                journalFlag &&
                permissionList.detail_confirm
                  ? true
                  : false
              "
              type="success"
              size="medium"
              @click="submitForm('ruleForm')"
              style="margin-left: 80px; margin-right: 130px"
              >确认订单</el-button
            >
          </el-col>
        </div>
      </div>
    </el-form>
    <!------------- 退订 --------------  -->
    <el-dialog
      title
      :visible.sync="returnGoodsFlag"
      :before-close="unsubscribeFormClose"
      center
      :append-to-body="true"
      :lock-scroll="false"
      width="50%"
      z-index="2007"
    >
      <div style="width: 100%; height: 430px">
        <el-scrollbar class="page-component__scroll" style="height: 400px">
          <el-col style="margin-top: 1%">
            <!-- <returnGoods v-bind:my-message="returnGoodsFlag"></returnGoods> -->
            <el-col style="margin-top: 1%">
              <div class="order-message" style="height: 35px">
                <el-col style="padding-left: 5px; font-size: 20px">退订</el-col>
              </div>
              <div style="height: 300px; margin-left: 25px">
                <el-form
                  :model="unsubscribeForm"
                  :rules="unsubscribefRules"
                  ref="unsubscribeForm"
                  label-width="100px"
                  class="demo-ruleForm"
                >
                  <el-form-item label="退订选项">
                    <el-checkbox-group v-model="unsubscribeForm.orderDetailIds">
                      <el-checkbox v-for="(item,index) in shoplist" v-show="(item.goodsTypeName != '服务费')" :key="index" :label="item.id"
                        :value="item.id" name="type" style="word-break: break-all;word-wrap:break-word;white-space: inherit;"
                        :disabled="(!!item.refundNotReturn || item.productionState == 10 || item.productionState == 11 || item.productionState == 12)">
                        <el-tag effect="plain" class="mr-5" size="mini">{{item.goodsTypeName}}</el-tag>
                        <span>{{ item.goodsName }}(规格：{{ item.goodsSpecs }},价格：{{ (item.totalPrice/100).toFixed(2) }})</span>
                        <el-tag type="danger" size='small' v-if='item.refundNotReturn'> {{item.refundNotReturn}}</el-tag>
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  <el-form-item label="退订原因" prop="unsubscribeReason">
                    <el-select
                      v-model="unsubscribeForm.unsubscribeReason"
                      placeholder="请选择退订原因"
                    >
                      <el-option
                        v-for="(item, index) in returnOrderReasonList"
                        :key="index"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="是否生产" prop="isProduction">
                    <el-select
                      v-model="unsubscribeForm.isProduction"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="(item, index) in whetherProduceList"
                        :key="index"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="蛋糕去向" prop="cakeWhereabouts">
                    <el-select
                      v-model="unsubscribeForm.cakeWhereabouts"
                      placeholder="请选择蛋糕去向"
                    >
                      <el-option
                        v-for="(item, index) in cakeWhereaboutsList"
                        :key="index"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="申请原因" prop="applyReason">
                    <el-input
                      type="textarea"
                      v-model.trim="unsubscribeForm.applyReason"
                      placeholder="请输入申请原因"
                      maxlength="50"
                      :autosize="{ minRows: 3 }"
                      style="width: 350px"
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="unsubscribeResetForm('unsubscribeForm')"
                      >取消</el-button
                    >
                    <el-button
                      :data-id="ruleForm.id"
                      type="primary"
                      @click="unsubscribeSubmitForm($event, 'unsubscribeForm')"
                      >确定</el-button
                    >
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-col>
        </el-scrollbar>
      </div>
    </el-dialog>
    <!------------- 退款 --------------  -->
    <el-dialog
      :title="RefundShowFlag ? '退款' : '退款不退货'"
      :visible.sync="refundOpenFlag"
      :before-close="refundFormClose"
      :append-to-body="true"
      :lock-scroll="false"
      width="75%"
      z-index="2007"
    >
      <div>
        <el-scrollbar class="page-component__scroll" style="height: 400px">
          <el-col style="margin-top: 1%">
            <el-col style="margin-top: 1%">
              <div style="height: 300px; margin-left: 25px">
                <el-form
                  :model="refundForm"
                  :rules="refundrules"
                  ref="refundForm"
                  label-width="100px"
                  class="demo-ruleForm"
                >
                  <el-form-item style="margin-left: -99px">
                    <el-col class="formType">
                      <el-form-item label="后台单号">
                        <div style="width: 198px">{{ ruleForm.xmbzNo }}</div>
                      </el-form-item>
                      <el-form-item label="订单状态">
                        <el-input
                          v-model.trim="ruleForm.statusName"
                          disabled=""
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col v-if="showRefundWay">
                      <el-form-item label="退款方式">
                        <el-radio v-model="refundForm.refundWay" label="1">正常退款</el-radio>
                        <el-radio v-model="refundForm.refundWay" label="2">搭售退款</el-radio>
                      </el-form-item>
                    </el-col>
                    <el-col>
                      <el-form-item label="退款选项" required>
                        <el-checkbox-group
                          v-if="refundForm.refundWay == 1"
                          class="refundcake"
                          v-model="refundForm.selectOrderDetailIds"
                          @change="getTotalprice"
                        >
                          <div class="mb-10" v-if="filterRefundList && filterRefundList.length" v-for="(group, index) in filterRefundList" :key="group.mainId">
                            <div class="refund-order-box">
                              <el-checkbox
                                  v-for="(item, index) in group.list"
                                  :key="index"
                                  :label="item.id"
                                  :value="item.id"
                                  name="type"
                                  :disabled="item.refundIdentification === '已退款'"
                                >
                                <el-tag effect="plain" class="mr-5" size="mini">{{item.categoryName}}</el-tag>
                                <span>
                                  {{ item.goodsName }}
                                  (规格：{{ item.goodsSpecs }}
                                  价格：{{(item.totalPrice / 100).toFixed(2)}})
                                </span>
                                <span v-if="group.mainId == item.workRefundId">
                                  <agianRefundInfo :detail="item"></agianRefundInfo>
                                  <span v-show="showAgainRefundBtn(item)">
                                    <el-button class="ml-5" size="mini" @click="handleRefundAgain(item)">再次发起退款</el-button>
                                  </span>
                                </span>
                              </el-checkbox>
                            </div>
                          </div>
                        </el-checkbox-group>

                        <el-checkbox-group
                          v-if="refundForm.refundWay == 2"
                          class="tying-cake"
                          v-model="refundForm.tyingSales">
                          <div v-for="(item) in refundTyingList" :key="item.id" class="tying-item d-f ai-c mb-10">
                            <el-checkbox :label="item.id" :disabled="!!item.tyingRefundContent">
                              <span>{{ item.goodsName }}</span>
                            </el-checkbox>
                            <xm-select v-model="item.tyingCheckeds" :options="tyingSaleTypeList" multiple clearable placeholder="请选择搭售商品" :disabled="!!item.tyingRefundContent"></xm-select>
                            <el-tag class="ml-5" size="mini" type="danger" v-show="!!item.tyingRefundContent">已退款</el-tag>
                          </div>
                        </el-checkbox-group>
                      </el-form-item>
                    </el-col>
                    <el-col class="formType">
                      <el-form-item label="退款类型" prop="refundType">
                        <el-select
                          v-model="refundForm.refundType"
                          filterable 
                          placeholder="请选择退款类型"
                          @change="onRefundTypeChange"
                        >
                          <el-option
                            v-for="item in getRefundTypeList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          >
                          </el-option>
                        </el-select>
                        <span v-if="refundForm.refundType == '超时'" style="display: inline-block; width: 180px; margin-left: 2px">
                          <el-select v-model="refundForm.rangeLevel" @change="onTimeOutChange">
                            <el-option v-for="item in deliveryTimeOut" :key="item.value" :label="item.label" :value="item.value"></el-option>
                          </el-select>
                        </span>
                      </el-form-item>
                      <!-- <el-form-item label="蛋糕去向" prop="cakeWhereabouts">
                        <el-select
                          v-model="refundForm.cakeWhereabouts"
                          placeholder="请选择蛋糕去向"
                        >
                          <el-option
                            v-for="(item, index) in cakeWhereaboutsList"
                            :key="index"
                            :label="item.dictValue"
                            :value="item.dictKey"
                          ></el-option>
                        </el-select>
                      </el-form-item> -->
                    </el-col>
                    <el-col class="formType">
                      <el-form-item label="退款原因" prop="refundReason">
                        <el-select
                          v-model="refundForm.refundReason"
                          placeholder="请选择退款原因"
                        >
                          <el-option
                            v-for="(item, index) in getRefundReasonList"
                            :key="index"
                            :label="item.label"
                            :value="item.value"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="退款等级" prop="refundGrade">
                        <el-select
                          v-model="refundForm.refundGrade"
                          placeholder="请选择退款等级"
                        >
                          <el-option
                            v-for="(item, index) in getRefundGradeList"
                            :key="index"
                            :label="item.dictValue"
                            :value="item.dictKey"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <!-- <el-col class="formType">
                      <el-form-item label="退款方式" prop="refundMode">
                        <el-radio-group v-model="refundForm.refundMode">
                          <el-radio
                            v-for="(item,index) in radioList"
                            :key="index"
                            :label="item.dictKey"
                            :data-dictKey="item.dictKey"
                            @change="getRadio(item.dictKey)"
                          >
                          <span>{{ item.dictValue }}</span>
                          </el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col> -->
                    <!-- <el-col v-if="refundRadioFlag" class="formType"> -->
                    <el-col class="formType">
                      <el-form-item label="退款金额" prop="refundMoney">
                        <el-input
                          v-model="refundForm.refundMoney"
                          placeholder="请输入金额"
                          @input="refundForm.refundMoney=refundForm.refundMoney.replace(/[^\d.]/g,'')"
                          maxlength="10"
                          show-word-limit
                          style="width: 200px"
                        >
                          <span slot="suffix" style="moneyStyle">元</span>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col class="formType">
                      <el-form-item label="赔偿方式">
                        <el-radio-group v-model="refundForm.compensationMethod">
                          <el-radio
                            v-for="(item, index) in getCompensationMethodList"
                            :key="index"
                            :label="item.dictKey"
                            @change="getcompensationMethodRadio(item.dictKey)"
                          >
                            <span>{{ item.dictValue }}</span>
                          </el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <!-- <el-col v-if="compensationMethodFlag" style="margin-left: 50px;"> -->
                    <el-col style="margin-left: 50px">
                      <el-form-item
                        label="金额"
                        label-width="80px"
                        prop=""
                        style="margin-bottom: 10px; margin-left: 20px"
                      >
                        <el-input
                          v-model.trim="refundForm.cakeCompensatePrice"
                          placeholder="金额"
                          oninput="value=value.replace(/[^\d.]/g,'')"
                          maxlength="10"
                          show-word-limit
                          style="width: 200px"
                        ><span slot="suffix" style="moneyStyle">元</span></el-input>
                      </el-form-item>
                      <el-form-item
                        label="诚意金"
                        style="line-height: 5; margin-top: 20px"
                      >
                        <el-input
                          v-model="refundForm.sincerityGold"
                          placeholder="请输入诚意金"
                          oninput="value=value.replace(/[^\d.]/g,'')"
                          maxlength="10"
                          show-word-limit
                          style="width: 200px"
                        ><span slot="suffix" style="moneyStyle">元</span></el-input>
                      </el-form-item>
                      <el-form-item
                        label="赠送蛋糕"
                        style="line-height: 5; margin-top: 20px"
                      >
                        <el-input
                          v-model.number="refundForm.giveCakePrice"
                          placeholder="请输入金额"
                          oninput="value=value.replace(/[^\d.]/g,'')"
                          maxlength="10"
                          show-word-limit
                          style="width: 200px"
                        ><span slot="suffix" style="moneyStyle">元</span></el-input>
                      </el-form-item>
                      <el-form-item
                        label="赠送礼品"
                        style="line-height: 5; margin-top: 20px"
                      >
                        <el-input
                          v-model="refundForm.giveGiftPrice"
                          placeholder="请输入金额"
                          oninput="value=value.replace(/[^\d.]/g,'')"
                          maxlength="10"
                          show-word-limit
                          style="width: 200px"
                        ><span slot="suffix" style="moneyStyle">元</span></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col class="formType">
                      <el-form-item label="渠道">
                        <div style="width: 198px">
                          {{ ruleForm.channelName }}
                        </div>
                      </el-form-item>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="申请原因" prop="applyReason">
                    <el-input
                      type="textarea"
                      v-model.trim="refundForm.applyReason"
                      maxlength="50"
                      placeholder="请输入申请原因"
                      :autosize="{ minRows: 3 }"
                      style="width: 350px"
                      show-word-limit
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="平台门店" prop="store">
                    <el-input
                      type="textarea"
                      v-model.trim="refundForm.store"
                      placeholder="请输入平台门店"
                      maxlength="30"
                      show-word-limit
                      autosize
                      style="width: 200px"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="退款二维码">
                    <el-upload
                      list-type="picture-card"
                      action="/api/xmbz-goods/file/upload"
                      :data="{ tag: 'good' }"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                    >
                      <img
                        v-if="temp.mainPic && temp.mainPic.length"
                        :src="temp.mainPic"
                        class="avatar"
                      />
                      <i v-else class="el-icon-plus"></i>
                    </el-upload>
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-col>
        </el-scrollbar>
      </div>

      <div slot="footer" class="ta-r">
        <el-button @click="refundResetForm('refundForm')"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="refundSubmitForm($event, 'refundForm')"
          >申请退款</el-button
        >
      </div>
    </el-dialog>
    <!------------- 恢复订单 --------------  -->
    <el-dialog
      title
      :visible.sync="recoverOrderFlag"
      center
      :append-to-body="true"
      :lock-scroll="false"
      width="420px"
      z-index="2007"
    >
      <div style="width: 100%">
        <div class="order-message" style="height: 35px; border-bottom: 0">
          <el-col style="padding-left: 5px; font-size: 20px">恢复订单</el-col>
        </div>
        <el-form
          :model="recoverForm"
          ref="recoverForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- <el-form-item> -->
          <div style="font-size: 17px; margin-left: 5px">
            您确认要恢复订单吗？
          </div>
          <!-- </el-form-item> -->
          <el-form-item
            style="margin-top: 7%; display: flex; justify-content: flex-end"
          >
            <el-button @click="recoverResetForm('recoverForm')">取消</el-button>
            <el-button
              type="primary"
              :data-id="ruleForm.id"
              @click="recoverSubmitForm($event, 'recoverForm')"
              >确定</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!------------- 催单 --------------  -->
    <remindDialog ref="remindDialog" :ruleForm="ruleForm"></remindDialog>
    <!------------- 备款 --------------  -->
    <el-dialog
      title
      :visible.sync="frmLossFlag"
      center
      :append-to-body="true"
      :lock-scroll="false"
      width="60%"
      z-index="2007"
    >
      <div style="width: 100%; min-height: 600px">
        <el-scrollbar class="page-component__scroll" style="height: 500px">
          <el-col style="margin-top: 1%">
            <el-col style="margin-top: 1%">
              <div class="order-message" style="height: 35px">
                <el-col style="padding-left: 5px; font-size: 20px">备款</el-col>
              </div>
              <div style="height: 300px; margin-left: 25px">
                <el-form
                  :model="frmLossForm"
                  :rules="frmLossrules"
                  ref="frmLossForm"
                  label-width="100px"
                  class="demo-ruleForm"
                >
                  <el-form-item label="后台单号">
                    <div>{{ ruleForm.xmbzNo }}</div>
                  </el-form-item>
                  <el-form-item label="备款来源" prop="provisionsOperation">
                    <el-select
                      v-model="frmLossForm.provisionsOperation"
                      placeholder="请选择备款来源"
                      @input="idProvisionsOperation()"
                    >
                      <el-option
                        v-for="(item, index) in getSourceList"
                        :key="index"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    v-show="refundCakeFlag"
                    label="备款蛋糕"
                    style="height: 100%"
                  >
                    <el-checkbox-group
                      class="refundcake"
                      v-model="frmLossForm.orderDetailIds"
                    >
                      <el-checkbox
                        v-for="(item, index) in shoplist"
                        v-show="
                          item.goodsTypeName == '蛋糕' &&
                          item.productionState !== 10 &&
                          item.productionState !== 11
                        "
                        :key="index"
                        :label="item.id"
                        :value="item.id"
                        name="type"
                        style="
                          width: 325px;
                          word-break: break-all;
                          word-wrap: break-word;
                          white-space: inherit;
                          display: flex;
                          margin-top: 15px;
                        "
                        >{{ item.goodsName }}(规格：{{
                          item.goodsSpecs
                        }},价格：{{ item.originalPrice }})</el-checkbox
                      >
                    </el-checkbox-group>
                  </el-form-item>
                  <el-form-item
                    label="责任部门"
                    prop="personDept"
                    style="margin-top: 8px"
                  >
                    <el-select
                      v-model="frmLossForm.personDept"
                      placeholder="请选择部门"
                    >
                      <el-option
                        v-for="(item, index) in frmLossList"
                        :key="index"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="责任人" prop="personLiable">
                    <el-input
                      v-model.trim="frmLossForm.personLiable"
                      placeholder="请输入责任人"
                      maxlength="10"
                      show-word-limit
                      style="width: 200px"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="蛋糕去向" prop="cakeWhereabouts">
                    <el-select
                      v-model="frmLossForm.cakeWhereabouts"
                      placeholder="请选择蛋糕去向"
                    >
                      <el-option
                        v-for="(item, index) in cakeWhereaboutsList"
                        :key="index"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="备款内容" prop="provisionsContent">
                    <el-input
                      type="textarea"
                      v-model.trim="frmLossForm.provisionsContent"
                      :autosize="{ minRows: 3 }"
                      maxlength="50"
                      show-word-limit
                      style="width: 350px"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="是否生产" prop="isProduction">
                    <el-select
                      v-model="frmLossForm.isProduction"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="(item, index) in whetherProduceList"
                        :key="index"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    v-show="!frmLossTimeFlag"
                    class="Star-beacon"
                    label="退订原因"
                  >
                    <el-select
                      v-model="frmLossForm.unsubscribeReason"
                      placeholder="请选择退款原因"
                    >
                      <el-option
                        v-for="(item, index) in returnOrderReasonList"
                        :key="index"
                        :label="item.dictValue"
                        :value="item.dictKey"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    v-show="!frmLossTimeFlag"
                    class="Star-beacon"
                    label="申请原因"
                  >
                    <el-input
                      type="textarea"
                      v-model.trim="frmLossForm.applyReason"
                      placeholder="请输入申请原因"
                      :autosize="{ minRows: 3 }"
                      maxlength="50"
                      show-word-limit
                      style="width: 350px"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    v-show="frmLossTimeFlag"
                    label="配送时间"
                    class="el-form-item-class Star-beacon"
                  >
                    <div style="display: flex; margin-left: -10px">
                      <el-date-picker
                        type="date"
                        size="medium"
                        :placeholder="getdelOrderStartTime"
                        v-model="getdeliveryStartTime"
                        :picker-options="pickerOptionsStart"
                        value-format="yyyy-MM-dd "
                        format="yyyy-MM-dd "
                        :disabled="
                          orderStatus == 8
                        "
                        :clearable="false"
                        style="width: 170px; margin: 0 0 0 10px"
                      ></el-date-picker>
                      <div class="line" :span="1" style="margin: 0 10px">-</div>
                      <selecttime
                        ref="getdeliveryTime"
                        v-bind:disable="false"
                        v-bind:deliveryTime="getdeliveryStartTime"
                        v-bind:OrderStartTime="ruleForm.deliveryStartTime"
                        v-bind:OrderEndTime="ruleForm.deliveryEndTime"
                        style="width: 170px; margin: 0"
                      ></selecttime>
                    </div>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="frmLossResetForm('frmLossForm')"
                      >取消</el-button
                    >
                    <el-button
                      :data-id="ruleForm.id"
                      :data-orderId="ruleForm.orderId"
                      type="primary"
                      @click="frmLossSubmitForm($event, 'frmLossForm')"
                      >提交</el-button
                    >
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-col>
        </el-scrollbar>
      </div>
    </el-dialog>
    <!------------- 投诉 --------------  -->
    <complainDialog ref="complainDialog"></complainDialog>
    <!------------- 编辑商品 --------------  -->
    <editGoodsDialog ref="editGoodsDialog" :ruleForm="ruleForm" @onGoodsSubmit="handleGoodsSumbit" :onlyEditParts="onlyEditParts"></editGoodsDialog>
    
    <!-- 打标弹框 标签 -->
    <setLabelDialog ref="setLabelDialog" :orderId="orderId"></setLabelDialog>

    <reasonDialog
      ref="reasonDialog"
      title="转接理由"
      :orderId="orderId"
      :ruleForm="ruleForm"
    ></reasonDialog>

    <button style="position: fixed; left: -100%;" ref="emptyBtn">用于foucs</button>
    <addConsultHappyDialog ref="addConsultHappyDialog"></addConsultHappyDialog>
    <navMenu class="nav-menu" :orderId="orderId" v-if="orderId"></navMenu>
    <againRefundDialog ref="againRefundDialog" @confirm="refundOpenFlag = false"></againRefundDialog>
    <orderLogDialog ref="orderLogDialog"></orderLogDialog>
    <updateWorkGoodsDialog ref="updateWorkGoodsDialog" @submit="confirmTypeOrder(`保存成功，单号${ruleForm.xmbzNo}`)"></updateWorkGoodsDialog>
  </div>
</template>
<script>
import {
  orderList, // 查询
  detailList, // 订单详情
  getResponsibleDepartmentList, // 备款责任部门
  getCakeWhereaboutsList, // 蛋糕去向
  getProvisionsOperationList, // 备款来源
  addWorkOrderProvisions, // 新增备款（选择退订）
  getUnsubscribeReasonList, // 退订原因列表
  getIsProductionList, // 是否生产
  addWorkOrderUnsubscribe, // 新增退订
  getRefundGradeList, // 退款等级列表
  getRefundReasonList, // 退款原因列表
  getRefundTypeList, // 退款类型列表
  getRefundTypeReasonList,
  getFullRefundList, // 全额退款列表
  getCompensationMethodList, // 赔偿方式列表
  getRefundModeList, // 退款方式列表
  addWorkOrderRefund, // 新增退款
  addRefundNotReturn, // 新增退款不退货
  getRecoveryOrder, // 恢复订单
  updateByProvisions, // 修改订单状态
  updateList, // 确认订单
  getCategories, // 商品类型列表
  refundUnsubscribeConfirmOrder, // 退订退款请求修改
  getGoodsByOrderId, // 根据订单号,查询商品列表(退款)
  deleteOrderExt, // 平台退款中
  unlockOrder, //解锁
  getWarehouseListByCityId, // 为了获取城市的名称
  clientAddWorkOrderUnsubscribe,
  validateOrder,
  orderSubmitGoodsTime,
  add0rderOperateLog,
  listTyingSaleProducts,
  validateReplacementOrder,
} from "@/api/pending";
import {
  citySelect, // 城市
  getOrderChannelList, // 渠道
  getOrderChannelTypeList, // 渠道类别列表
  getSurplusWarehouseLoadList, // 仓库剩余负荷列表
  getMainWarehouseList, // 获取分仓
  getSeparateWarehouseList, // 获取分仓
  getWarehouseName, // 根据经度纬度，返回分仓总仓名称
  judgeGoodsClose, // 判断当前商品是否关闭
  getCloseAndDeliveryList, // 提取关闭接单时间
} from "@/api/createOrder";
import { getWarehouseList, getWarehouseByType } from "@/api/warehouse";
import { getUrlKey } from "@/util/getUrlKey.js";
import deliveryTime from "@/components/foundorder/deliverytime";
import reasonDialog from "@/components/order-detail/components/reasonDialog";
import Pagination from "@/components/Pagination"; // 分页
import selecttime from "@/components/foundorder/selecttime"; // 配送时间组件
import { mapGetters } from "vuex";
import { staffForward } from "@/api/workorder";
import Clickoutside from 'element-ui/src/utils/clickoutside'
import editGoodsDialog from './components/editGoodsDialog'
import complainDialog from './components/complainDialog'
import navMenu from './components/navMenu'
import { getWarehouseLabel, inputTipThrottle } from '@/util/map'
import axios from 'axios'
import addConsultHappyDialog from '@/views/workOrder/consultHappy/addDialog'
import { getCacheData } from '@/const/cacheData'
import diyCakeInfo from '@/components/order/diyCakeInfo'
import goodsItem from './components/goodsItem'
import {workAskTransportList} from "@/api/workorder/consultHappy";
import againRefundDialog from './components/againRefundDialog'
import orderLogDialog from '@/components/dialog/orderLogDialog'
import agianRefundInfo from "./components/againRefundDialog/agianRefundInfo.vue";
import setLabelDialog from "./components/setLabelDialog";
import remindDialog from "./components/remindDialog";
import { consultHappyDisposeType } from '@/const';
import updateWorkGoodsDialog from './components/updateWorkGoodsDialog';

export default {
  directives: {
    Clickoutside
  },
  components: {
    deliveryTime,
    Pagination,
    selecttime,
    reasonDialog,
    editGoodsDialog,
    addConsultHappyDialog,
    navMenu,
    complainDialog,
    diyCakeInfo,
    goodsItem,
    againRefundDialog,
    orderLogDialog,
    agianRefundInfo,
    setLabelDialog,
    remindDialog,
    updateWorkGoodsDialog,
  },
  data() {
    let checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("号码不能为空"));
      }
      var reg = /^1[3456789]\d{9}$/;
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else if (value.toString().length !== 11) {
          callback(new Error("号码长度应为11位"));
        } else if (!reg.test(value)) {
          callback(new Error("手机号码格式有误"));
        } else {
          callback();
        }
      }, 1000);
    };
    let receiverAddress = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("地址不能为空"));
      } else {
        this.ruleForm.receiverAddress = value.replace(/\s+/g, "");
        callback();
      }
    };
    var checkData = (rule, value, callback) => {
      if (value) {
        if (/[\u4E00-\u9FA5]/g.test(value)) {
          this.ruleForm.sumPrice = "";
          callback(new Error("编码不能输入汉字!"));
        } else {
          callback();
        }
      }
      callback();
    };
    // 校验定制信息
    let validateDiyData = (rule, value, callback) => {
      if (this.showCustomMade) {
        const diyData = this.$refs.diyCakeInfo.getDiyData()
        if (!diyData.diyCakeName) {
          callback(new Error("请填写订制商品名称!"));
        }
        if (diyData.diyCakeNum + 0 <= 0) {
          callback(new Error("请填写订制商品数量!"));
        }
        if (
          (diyData.diyCakeName == "定制米数蛋糕" ||
          diyData.diyCakeName == "定制多层蛋糕") &&
         (!diyData.diyCakeMeter)  
        ) {
          callback(new Error("请填写订制商品规格!"));
        }
        callback()
      }
    }
    return {
      consultHappyDisposeType,
      // 正则
      wareHouseTime: [], // 获取时间列表
      singcomplaintForm: {
        //投诉图片数组
        pics: [],
      },
      options: [], // 操作合并数组
      warehouseValue: "", // 操作内容
      orderId: "",
      shoplist: [],
      deptId: getUrlKey("cityId") !== 1 ? getUrlKey("cityId") : "",
      deptName: getUrlKey("deptName") !== "全国" ? getUrlKey("deptName") : "",
      cityselect: "", // 城市获取列表
      ruleForm: {
        totalPrice: "",
        sumPrice: "",
        channel: "",
        receiverDetailAddress: "",
        channelType: "",
        // wareHouse: '', // 用来获取分仓的参数
        branchWarehouse: "", // 分仓
        orderDetailRequests: [],
      },
      rules: {
        channelType: [
          { required: true, message: "请选择渠道类型", trigger: "blur" },
        ],
        channel: [{ required: true, message: "请选择渠道", trigger: "blur" }],
        sumPrice: [
          { required: true, message: "请输入价格", trigger: "blur" },
          { validator: checkData, trigger: "change" },
        ],
        receiverName: [
          { required: true, message: "请输入收货人", trigger: "blur" },
        ],
        receiverPhone: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
        ],
        mainWarehouse: [
          { required: true, message: "请选择仓库", trigger: "blur" },
        ],
        branchWarehouse: [
          { required: true, message: "请选择仓库", trigger: "blur" },
        ],
        receiverAddress: [
          { required: true, validator: receiverAddress, trigger: "change" },
        ],
        diyCakeName: [
          { required: true, validator: validateDiyData, trigger: "blur" },
        ],
      },

      updateByProvisionsList: {
        // 修改订单状态列表
        orderId: "",
        workOrderProvisionsIds: [],
      },
      channerllist: "", //渠道
      addressFlagcopy: false, // 地址列表
      addressList: "",
      currentIndex: "", // 选中对应的索引
      pagesize: 5,
      currentPage: 1,
      detailLoading: true,
      channelTypellist: "", // 渠道类别列表
      citylist: "", // 下单仓库中的总仓
      abbrlist: "", // 分仓
      getMainWarehouseList: {
        parentId: "",
      },
      // 分仓
      getSeparateWarehouseList: {
        deptId: 1,
      },
      getWarehouseName: {
        // 根据经度纬度，返回分仓总仓名称
        longitude: 1,
        latitude: 2,
      },
      orderFlag: false, //恢复订单
      returnGoodsFlag: false, // 退订Flag
      refundCakeFlag: false, // 退款
      returnOrderReasonList: "", //退订原因列表
      whetherProduceList: "", //是否生产列表
      cakeWhereaboutsList: "", //蛋糕去向列表
      // 退订
      unsubscribeForm: {
        orderId: 1,
        orderDetailIds: [], //xiangqign id
        selectOrderDetailIds: [], // 选中的订单明细id的集合
        noSelectOrderDetailIds: [], // 初始未选择的订单明细id的集合
        unsubscribeReason: "",
        isProduction: "",
        cakeWhereabouts: "", // 蛋糕去向
        applyReason: "", // 申请原因
      },
      unsubscribefRules: {
        unsubscribeReason: [
          { required: true, message: "请选择退订原因", trigger: "blur" },
        ],
        isProduction: [
          { required: true, message: "请选择生产状态", trigger: "change" },
        ],
        applyReason: [
          { required: true, message: "请输入申请原因", trigger: "change" },
        ],
        cakeWhereabouts: [
          { required: true, message: "请选择蛋糕去向", trigger: "change" },
        ],
        orderDetailIds: [
          {
            required: true,
            message: "请至少选择一个蛋糕",
            trigger: "change",
          },
        ],
      },
      refundOpenFlag: false, // 退款Flag
      refundCakePrice: "", // 所选中的退款蛋糕的总价
      refundRadioFlag: true, // 退款金额标记
      payforRadioFlag: false, // 赔偿方式中赔偿的标记
      compensationMethodFlag: false, // 赔偿方式标记
      getRefundGradeList: "", // 退款等级列表
      getRefundReasonList: "", // 退款原因列表
      getRefundTypeList: [], // 退款类型列表
      deliveryTimeOut: [ 
        { value: 1, label: '轻度 超时40分钟内'},
        { value: 2, label: '中等 超时90分钟内'},
        { value: 3, label: '严重 超时90分钟以上'}
      ],
      getCompensationMethodList: "", // 赔偿方式列表
      temp: {
        name: "",
        categoryId: "",
        mainPic: "",
        description: "",
        goodsSkuRequests: [],
        pics: [],
      },
      radioList: [
        // 退款方式
        {
          dictKey: 1,
          dictValue: "退款",
        },
        {
          dictKey: 2,
          dictValue: "赔偿",
        },
      ],
      refundForm: {
        // 退款
        orderId: 1, // 订单
        selectOrderDetailIds: [], // 订单明细id的集合
        // platformNo: "", // 平台单号
        refundReason: "", // 退款原因
        // channel: "", // 退款渠道
        isProduction: "", // 是否生产
        cakeWhereabouts: "", // 蛋糕去向
        refundType: "", // 退款类型
        rangeLevel: "", // 退款类型-二级
        refundGrade: 1, // 退款等级
        // fullRefund: "", // 全额退款
        refundMoney: "", // 退款金额
        sincerityGold: "", // 诚意金
        compensationMethod: "", // 赔偿方式
        cakeCompensatePrice: 0, // 赔偿中的金额
        // typeKind: [],
        applyReason: "", // 申请原因
        refundCode: "", // 退款二维码
        store: "", // store
        refundMode: "", // 退款方式 1:退款 2:赔偿:refundMode
        giveCakePrice: "", // 赠送的蛋糕价格
        giveGiftPrice: "", // 赠送的礼品价格
        refundWay: '1', // 退款方式
        tyingSales: [],
      },
      refundrules: {
        refundReason: [
          { required: true, message: "请选择退款原因", trigger: "change" },
        ],
        isProduction: [
          { required: true, message: "请选择生产状态", trigger: "change" },
        ],
        cakeWhereabouts: [
          { required: true, message: "请选择蛋糕去向", trigger: "change" },
        ],
        refundType: [
          { required: true, message: "请输入退款类型", trigger: "change" },
        ],
        refundGrade: [
          { required: true, message: "请输入退款等级", trigger: "change" },
        ],
        // fullRefund: [
        //   { required: true, message: "请选择全额退款", trigger: "change" }
        // ],
        refundMoney: [{ required: true, message: "金额不能为空" }],
        sincerityGold: [
          { required: true, message: "金额不能为空" },
          { type: "number", message: "金额必须为数字值" },
        ],
        compensationMethod: [
          {
            required: true,
            message: "请至少选择一个赔偿方式",
            trigger: "change",
          },
        ],
        store: [
          { required: true, message: "请输入平台门店", trigger: "change" },
        ],
        refundCode: [
          { required: true, message: "请上传二维码", trigger: "change" },
        ],
        refundMode: [
          { required: true, message: "请选择活动资源", trigger: "change" },
        ],
        orderDetailIds: [
          {
            required: true,
            message: "请至少选择一个蛋糕",
            trigger: "change",
          },
        ],
      },
      recoverOrderFlag: false, // 恢复订单
      recoverForm: {
        // 恢复订单
        orderId: 132,
      },
      // 日期
      pickerOptionsStart: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      frmLossFlag: false, //备款
      frmLossList: "", // 备款责任部门列表
      getSourceList: "", // 备款来源列表
      frmLossTimeFlag: false, //备款（配送时间）按钮
      frmLossForm: {
        orderId: 1, //后台单号
        orderDetailIds: [], // 详情id
        personDept: "", //部门
        personLiable: "", //责任人
        cakeWhereabouts: "", //蛋糕去向
        provisionsContent: "", //备款内容
        provisionsOperation: "", //备款来源
        distributionStartTime: "", //配送时间
        distributionEndTime: "", //
        isProduction: "", // 是否生产
        // applyReason: "", // 申请原因
        // unsubscribeReason: "", // 退订原因
      },
      frmLossrules: {
        personDept: [
          { required: true, message: "请选择责任部门", trigger: "change" },
        ],
        personLiable: [
          { required: true, message: "请输入责任人", trigger: "change" },
        ],
        cakeWhereabouts: [
          { required: true, message: "请选择去向", trigger: "change" },
        ],
        provisionsContent: [
          { required: true, message: "请输入备款内容", trigger: "change" },
        ],
        isProduction: [
          { required: true, message: "请选择生产状态", trigger: "change" },
        ],
        provisionsOperation: [
          { required: true, message: "请输入备款来源", trigger: "change" },
        ],
        applyReason: [
          { required: true, message: "请输入申请原因", trigger: "change" },
        ],
        unsubscribeReason: [
          { required: true, message: "请选择退订原因", trigger: "change" },
        ],
        orderDetailIds: [
          {
            required: true,
            message: "请至少选择一个蛋糕",
            trigger: "change",
          },
        ],
      },
      complainFlag: false, //投诉
      getCategoriesList: [], //商品类型列表
      UnsubscribeFlag: false, // 退订标记
      refundFlag: false, // 退款标记
      latitude: "",
      longitude: "",
      latitudeFlag: false,
      orderStatus: "",
      preservationFlag: false, // 保存信息
      RefundShowFlag: false, // 退款请求接口标记
      RefundNoReShowFlag: false, // 退款不退货请求接口标记
      getdeliveryStartTime: "", // 时间
      getdelOrderStartTime: "", //订单时间
      refundList: [], // 退款商品列表查询（判断是否已退款）
      refundTyingList: [], // 退款搭售商品列表查询
      receiverDetailAddress: "", // 详细地址
      warehouseId: "", // 水库是否为空
      map: "", //地图
      timeNumbers: 0,
      isConfirmCancelOrder: false,
      tyingSaleTypeList: [],
      consultHappyOrderList: [], // 咨询快乐工单
    };
  },
  watch: {
    "ruleForm.warehouseId"() {
      getCloseAndDeliveryList({ wid: this.ruleForm.warehouseId }).then(
        (res) => {
          this.wareHouseTime = res.data.data;
        }
      );
    }
  },
  created() {
    this.orderId = getUrlKey('id')
    this.getList().then(() => {
      if (this.ruleForm.transportDisposeContent) {
        workAskTransportList({
          xmbzNo: this.ruleForm.xmbzNo
        }).then(res => {
          this.consultHappyOrderList = (res.data.data && res.data.data.rows) || []
        })
      }
    });
  },
  mounted() {
    this.cityId = JSON.parse(
      window.localStorage.getItem("saber-areaId")
    ).content;
    // 城市
    citySelect().then((res) => {
      this.cityselect = res.data.data;
    });
    // 渠道类别列表
    this.getOrderChannelTypeList();
    // 退订原因列表
    getUnsubscribeReasonList().then((res) => {
      this.returnOrderReasonList = res.data.data;
    });
    // 是否生产
    getIsProductionList().then((res) => {
      this.whetherProduceList = res.data.data;
    });
    // 蛋糕去向
    getCakeWhereaboutsList().then((res) => {
      this.cakeWhereaboutsList = res.data.data;
    });
    // 商品类型选择
    this.getCategories();
    // 点击页面空白处
    //关闭窗口时解锁订单
    window.addEventListener(
      "beforeunload",
      function (event) {
        window.opener.unlockOrder(getUrlKey("id"));
        return false;
      },
      true
    );
    // 进入此页面开始计时
    this.overTimeOrder();
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        detail_preservation: this.vaildData(
          this.permission.detail_preservation,
          false
        ),
        detail_provision: this.vaildData(
          this.permission.detail_provision,
          false
        ),
        detail_unsubscribe: this.vaildData(
          this.permission.detail_unsubscribe,
          false
        ),
        detail_refund: this.vaildData(this.permission.detail_refund, false),
        detail_returngoods: this.vaildData(
          this.permission.detail_returngoods,
          false
        ),
        detail_reminders: this.vaildData(
          this.permission.detail_reminders,
          false
        ),
        detail_complaint: this.vaildData(
          this.permission.detail_complaint,
          false
        ),
        detail_platformrefund: this.vaildData(
          this.permission.detail_platformrefund,
          false
        ),
        detail_confirm: this.vaildData(this.permission.detail_confirm, false),
        detail_edit_time: this.vaildData(
          this.permission.detail_edit_time,
          false
        ),
        detil_clone_order: this.vaildData(this.permission.clone_order, false),
      };
    },
    // 转接客服按钮
    transToCusBtnShow() {
      return this.ruleForm.status !== 16; // 改期（16）时不显示
    },
    // 商品类型列表
    goodsTypeNameList() {
      return this.shoplist && this.shoplist.map(item => item.goodsTypeName)
    },
    // 确认按钮
    journalFlag() {
      return this.ruleForm.status == 1
    },
    // 退订按钮
    returnOrderFlag() {
      let permission = false
      const status = this.ruleForm.status
      const goodsTypeNameList = this.goodsTypeNameList || []
      if (status == 1 || status == 4 || status == 5 || status == 7 || status == 8) {
        if (goodsTypeNameList.some(item => item != '服务费')) {
          permission = true
        }
      }
      return permission
    },
    // 退款按钮
    refundMoneyFlag() {
      let permission = false
      const status = this.ruleForm.status
      if ([1,4,5,7,8,6,9,11,12,13,16].includes(status)) {
        permission = true
      }
      return permission
    },
    // 退款不退货
    RefundNoReFlag() {
      let permission = false
      const status = this.ruleForm.status
      if ([4,5,6,7,8,9,13].includes(status)) {
        permission = true
      }
      return permission
    },
    // 催单按钮
    reminderOrderFlag() {
      return [4,5,6,7,12].includes(this.ruleForm.status)
    },
    // 备款按钮
    frmLossOrderFlag() {
      let permission = false
      const status = this.ruleForm.status
      const goodsTypeNameList = this.goodsTypeNameList || []
      if (status == 6) {
        if (goodsTypeNameList.some(item => item == '蛋糕')) {
          permission = true
        }
      }
      return permission
    },
    // 投诉按钮
    complainOrderFlag() {
      let permission = false
      const status = this.ruleForm.status
      if ([1,4,5,6,7,8,9,11,12,13,16].includes(status)) {
        permission = true
      }
      return permission
    },
    // 私人订制
    showCustomMade() {
      return this.shoplist && this.shoplist.some((item) =>
        item.goodsName.includes("私人订制")
      );
    },
    canEditGoods() {
      return (this.ruleForm.status == 1 && this.permission.detail_edit_goods) ||
              (this.permission.inquiry_edit_parts &&
                [1,4,5,6,7].some(item => item == this.ruleForm.status))
    },
    onlyEditParts() {
      return this.permission.inquiry_edit_parts &&
              [4,5,6,7].some(item => item == this.ruleForm.status)
    },
    showRefundWay() {
      return this.refundTyingList.length && this.RefundNoReShowFlag
    },
    // 搭售退款
    isTyingRefund() {
      return this.showRefundWay && this.refundForm.refundWay == 2
    },
    // 退款选项列表
    filterRefundList() {
      let list = []
      if (this.refundList && this.refundList.length) {
        const parentIds = Array.from(new Set(this.refundList.filter(item => item.workRefundParentId != '0' && item.workRefundParentId != -1).map(item => item.workRefundParentId)))
        if (parentIds && parentIds.length) {
          const groupList = parentIds.map(mainId => {
            return {
              mainId: mainId,
              list: this.refundList.filter(item => item.workRefundId == mainId || item.workRefundParentId == mainId)
            }
          })
          // 1.商品属于同一工单
          list = list.concat(groupList)
        }

        // 单个商品一个工单
        list = list.concat(this.refundList.filter(item => item.workRefundParentId == '0' && !parentIds.includes(item.workRefundId)).map(item => {
          return {
            mainId: item.workRefundId,
            list: [item]
          }
        }))

        // 未退的商品
        list = list.concat(this.refundList.filter(item => item.workRefundId == -1).map((item, index) => {
          return {
            mainId: item.workRefundId,
            list: [item]
          }
        }))
      }
      return list
    },
    canEditPay() {
      return this.permission['detail_edit_pay']
    },
    canEditChannel() {
      return this.permission['detail_edit_channel']
    }
  },
  methods: {
    onTimeOutChange() {
      console.log('refundForm.rangeLevel'+'::>>', this.refundForm.rangeLevel)
    },
    // 根据退款类型补充退款原因
    onRefundTypeChange(value) {
      const str = this.refundForm.refundType
      if(str != '超时') {
        console.log('进入'+'::>>', )
        this.refundForm.rangeLevel = ''
      }
      const refundTypeItem = this.getRefundTypeList.find(item => item.value === value)
      if (refundTypeItem && refundTypeItem.children && refundTypeItem.children.length) {
        this.getRefundReasonList = refundTypeItem.children.map(item => {
          return {
            label: item.reasonName,
            value: item.reasonKey,
            typeKey: item.typeKey,
          }
        })
        const selectFirst = refundTypeItem.children[0]
        this.refundForm.refundReason = selectFirst.reasonKey
      } else {
        this.getRefundReasonList = []
        this.refundForm.refundReason = ''
      }
    },
    // 退款类型列表
    async getRefundTypeReasonList() {
      const res = await getRefundTypeReasonList()
      this.getRefundTypeList = Object.keys(res.data.data).map(keys=>{
        return {
          label: keys,
          value: keys,
          children: res.data.data[keys]
        }
      })
    },
    // 定制信息blur
    handleDiyChange(diyInfo) {
      this.ruleForm.productionNotes = this.ruleForm.productionNotes.replace(/【订制信息：([\s\S]+)】/, '') + `【订制信息：${diyInfo}】`
    },
    changeDeliveryEndTime(startTime, endTime) {
      return `${startTime}~${endTime}`;
    },
    changeDeliveryStartTime(startTime, endTime, orderAdvanceTime) {
      var myDate = new Date();
      myDate = new Date(myDate.getTime() + orderAdvanceTime * 60 * 1000);

      var endDateTime = new Date();
      if (endTime === "00:00:00") {
        endDateTime.setHours(23);
        endDateTime.setMinutes(59);
      } else {
        endDateTime.setHours(endTime.substr(0, 2) * 1);
        endDateTime.setMinutes(endTime.substr(3, 2) * 1);
      }
      if (myDate.getTime() > endDateTime.getTime()) {
        return "不建议选择当天配送";
      }

      return (
        "当天配送建议选择配送时间：" +
        `${
          myDate.getHours() > 9 ? myDate.getHours() : `0${myDate.getHours()}`
        }:${
          myDate.getMinutes() > 9
            ? myDate.getMinutes()
            : `0${myDate.getMinutes()}`
        } - ` +
        endTime.substr(0, 5)
      );
    },
    copeOrder() {
      this.$message({
        type: "success",
        message: "复制成功",
      });

      setTimeout(() => {
        let routerJump = this.$router.resolve({
          path: "/copyOrder/index",
          query: this.$router.currentRoute.query,
        });
        window.open(routerJump.href, "_blank");
      }, 500);
    },

    // 创建变量方案
    changeselectBtn(data) {
      this.options = [];
      data.map((item, index) => {
        let obj = {};
        obj.label = item.deptName;
        obj.options = [];
        this.options.push(obj);
      });
      data.map((item, index) => {
        getSeparateWarehouseList({ deptId: item.id }).then((res) => {
          let arr = [];
          let dataNameList = data;
          res.data.data.map((item, index) => {
            let obj = {};
            obj.id = item.cityId;
            obj.deptId = item.deptId;
            obj.value = item.name;
            arr.push(obj);
          });
          this.options[index].options = arr;
        });
      });
    },

    getChannel(data) {
      // console.log('data',data)
      if (data) {
        this.ruleForm.channel = data.value;
        this.ruleForm.channelName = data.label;
      }
    },
    // 渠道类别列表
    getOrderChannelTypeList() {
      return getOrderChannelTypeList().then((res) => {
        this.channelTypellist = res.data.data;
      });
    },
    getOrderListParams() {
      const params = {
        deptId: this.ruleForm.deptId || this.deptId, // 城市id
        id: this.orderId,
        StartTime: "",
        EndTime: "",
        channelType: "",
        orderTimeSort: 0, // 下单时间排序
        deliveryTimeSort: 0, // 配送时间排序
        page: 1,
        limit: 10,
        size: 10,
        orderDetailRequests: [],
      }
      return params
    },
    getList() {
      this.getDetailList()
      return orderList(this.getOrderListParams()).then((res) => {
        let result = res.data.data.rows[0];
        this.ruleForm = {
          ...this.ruleForm,
          ...result
        };
        this.ruleForm.sumPrice = (
          result.totalPrice / 100
        ).toFixed(2);
        this.refundForm.refundMoney = (
          result.totalPrice / 100
        ).toFixed(2); // 退款金额默认值
        this.refundForm.store = res.data.data.rows[0].merchantName; // 退款门店默认值
        // 渠道类别列表
        this.getOrderChannelTypeList().then(() => {
          this.channelTypellist.forEach((item) => {
            if (item.channelKey == this.ruleForm.channelType) {
              // 获取渠道
              this.getOrderChannelList(item.id)
            }
          });
        });
        this.warehouseId = result.warehouseId || '';
        this.orderStatus = result.status;
        this.receiverDetailAddress = result.receiverAddress || '';
        this.deptId = result.deptId;
        this.getdelOrderStartTime = result.deliveryStartTime.slice(0, 11);
        if (this.getdelOrderStartTime !== "")
          this.getdeliveryStartTime = this.getdelOrderStartTime;
        this.$refs.diyCakeInfo && this.$refs.diyCakeInfo.setDiyData({
          diyCakeName: result.diyCakeName,
          diyCakeNum: result.diyCakeNum,
          diyCakeMeter: result.diyCakeMeter,
        })

        // 获取总仓
        this.getMainWarehouse(this.ruleForm.deptId);
        this.handleMapData()
        this.judgeOnHouseRange()
      });
    },
    getOrderChannelList(channelTypeId) {
      getOrderChannelList({parentId: channelTypeId}).then((res) => {
        this.channerllist = res.data.data;
      });
    },
    getDetailList() {
      this.detailLoading = true;
      detailList({orderId: this.orderId}).then((res) => {
        this.shoplist = res.data.data;
        this.shoplist.forEach((item) => {
          item.categoryIdArray = [];
          if (item.goodsSpecs == "") {
            item.goodsSpecsFlags = true;
          } else {
            item.goodsSpecsFlags = false;
          }
        });
        setTimeout(() => {
          this.detailLoading = false;
        }, 0.5 * 1000);
      });
    },
    // 处理地图元素
    handleMapData() {
      if (this.$refs.xmMap) {
        this.$refs.xmMap.clearMap()
        // 未点击城市时划区域
        if (this.ruleForm.deptId == 1) {
          this.ruleForm.deptId = "";
          this.addLocationMarkerOnMap();
        } else {
          this.addLocationMarkerOnMap();
          this.addWarehouseOnMap();
          this.addPlatformWarehouseOnMap();
        }
        this.$refs.xmMap.setCenter([this.ruleForm.longitude, this.ruleForm.latitude])
      }
    },
    // 判断是否在仓库配送范围
    judgeOnHouseRange() {
      const params = {
        latitude: this.ruleForm.latitude,
        longitude: this.ruleForm.longitude,
      }
      getWarehouseName(params).then((res) => {
        if (res.data.msg == "操作成功") {
          if (
            res.data.data.cityId !== this.ruleForm.deptId &&
            this.ruleForm.status == 1
          ) {
            this.$confirm(
              "您选择的地址不在配送范围内, 请联系用户，确认配送地址！",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
          }
        } else if (
          res.data.msg == "暂无承载数据" &&
          this.ruleForm.status == 1
        ) {
          this.$confirm(
            "您选择的地址不在配送范围内, 请联系用户，确认配送地址！",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
        }
      });
    },
    // 添加当前位置
    addLocationMarkerOnMap() {
      const marker = this.$refs.xmMap.createMarker({
        longitude: this.ruleForm.longitude,
        latitude: this.ruleForm.latitude,
        label: {
          content: `<div class='info'>${this.receiverDetailAddress}</div>`
        },
        icon: {
          image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png'
        },
        zIndex: 50
      })
      this.$refs.xmMap.map.add([marker])
    },
    // 添加当前分仓边界
    addWarehouseOnMap() {
      getWarehouseList({ cityId: this.ruleForm.deptId }).then(res => {
        const resData = res.data.data || [];
        if (resData && resData.length) {
          const markers = resData.map(item => {
            return this.$refs.xmMap.createMarker({
              longitude: item.longitude,
              latitude: item.latitude,
              label: {
                content: getWarehouseLabel(item)
              },
            })
          });

          const polygonPath = resData.map(item => {
            return item.geoJson.geometry.coordinates[0]
          })
          const polygon = this.$refs.xmMap.createPolygon({
            path: polygonPath,
            strokeColor: "#000",
            strokeWeight: 3,
            strokeOpacity: 1,
            fillOpacity: 0.4,
            fillColor: "#fff",
            zIndex: 40,
          });
          this.$refs.xmMap.map.add([...markers, polygon])
        }
      })
    },
    // 添加当前中央厨房
    addPlatformWarehouseOnMap() {
      getWarehouseByType({
        cityId: this.ruleForm.deptId,
        type: 99,
      }).then(res => {
        const resData = res.data.data || []
        if (resData && resData.length) {
          const markers = resData.map(item => {
            return this.$refs.xmMap.createMarker({
              longitude: item.longitude,
              latitude: item.latitude,
              label: {
                content: getWarehouseLabel(item)
              },
            })
          });

          const polygonPath = resData.map(item => {
            return item.geoJson.geometry.coordinates[0]
          })
          const polygon = this.$refs.xmMap.createPolygon({
            path: polygonPath,
            strokeColor: "#FF33FF",
            strokeWeight: 2,
            strokeOpacity: 1,
            fillOpacity: 0.4,
            fillColor: "#1791fc",
            zIndex: 50,
          });
          this.$refs.xmMap.map.add([...markers, polygon])
        }
      })
    },
    // 获取分仓id
    getwarehouseId(val) {
      this.ruleForm.warehouseId = val;
      this.judgeGoodsClose()
    },
    // 判断仓库是否关闭商品
    judgeGoodsClose() {
      if (this.shoplist && this.shoplist.length) {
        axios.all(this.shoplist.map(item => {
          return judgeGoodsClose({
            warehouseId: this.ruleForm.warehouseId,
            skuCode: item.skuCode
          })
        })).then(resList => {
          const resultDatas = resList.map(item => item.data.data)
          if (resultDatas.some(item => item)) {
            this.$message({
              type: "warning",
              message: "所选仓库没有生产该蛋糕的原料,请联系用户更换蛋糕",
            });
            this.ruleForm.branchWarehouse = "";
          }
        })
      }
    },
    // 下单仓库城市获取
    cityclick(data) {
      if (data) {
        this.deptName = data.label;
        this.ruleForm.deptId = data.value;
        this.ruleForm.deptName = data.label;
      }
      this.latitudeFlag = false;
      this.startArea(data.value);
      this.handleMapData();
    },
    startArea(datacity) {
      this.getMainWarehouseList.parentId = datacity;
      if (!this.latitudeFlag) {
        // 总仓
        getMainWarehouseList(this.getMainWarehouseList).then((res) => {
          let abbrResult = res.data.data;
          if (abbrResult.length > 0) {
            abbrResult.forEach((item) => {
              if (item.name == this.ruleForm.mainWarehouse) {
                this.ruleForm.mainWarehouse = item.name;
                this.citylist = abbrResult;
              } else {
                this.citylist = abbrResult;
                this.ruleForm.mainWarehouse = "";
                this.ruleForm.branchWarehouse = "";
              }
            });
          }
          this.changeselectBtn(abbrResult);
        });
      }
    },
    // 确认订单
    submitForm(formName) {
      this.$refs.emptyBtn.focus()
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.preservationFlag = false;
          this.UnsubscribeFlag = false;
          this.refundFlag = false;
          this.statusUpdate({operateType: 'confirm'});
        } else {
          this.$confirm("还有信息未填完整，请补充完整?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$message({
                type: "warning",
                message: "请完善信息!",
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消操作",
              });
            });
          return false;
        }
      });
    },
    // 保存信息
    preservation(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.preservationFlag = true;
          this.UnsubscribeFlag = false;
          this.refundFlag = false;
          const startTime = this.$refs.getdeliveryTime.deliveryTime + this.$refs.getdeliveryTime.getStartTime();
          let getDeliveryFlag = this.isTimeOverCurrent(startTime);
          if (getDeliveryFlag) {
            this.statusUpdate({operateType: 'preservation'});
          } else {
            this.$confirm("该配送时间已过期，是否继续修改订单?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              this.statusUpdate({operateType: 'preservation'});
            })
          }
        } else {
          this.$confirm("还有信息未填完整，请补充完整?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.$message({
                type: "warning",
                message: "请完善信息!",
              });
            })
        }
      });
    },
    handleRuleFormBeforeSave() {
      this.ruleForm.deliveryStartTime =
          this.$refs.getdeliveryTime.deliveryTime +
          this.$refs.getdeliveryTime.getStartTime();
      this.ruleForm.deliveryEndTime =
        this.$refs.getdeliveryTime.deliveryTime +
        this.$refs.getdeliveryTime.getEndTime();
      this.ruleForm.orderDetailRequests = this.shoplist;
      this.ruleForm.totalPrice = this.ruleForm.sumPrice * 100;
      this.ruleForm.originalPrice = this.ruleForm.sumPrice * 100;
      this.ruleForm.locationAddress = this.receiverDetailAddress; // 订单定位地址
      this.updateByProvisionsList.orderId =
        this.ruleForm.orderDetailRequests[0].orderId;
    },
    // 未确认必须重新选择时间，其他状态判断是否有时间
    statusUpdate({operateType} = {}) {
      this.handleRuleFormBeforeSave()
      const errorMsg = this.validateParams({isCheckBlessing: !(this.UnsubscribeFlag || this.refundFlag), isCheckTime: !(this.UnsubscribeFlag || this.refundFlag || this.preservationFlag)})
      if (errorMsg) {
        this.$confirm(errorMsg, "提示", {
          showCancelButton: false,
          confirmButtonText: "确定",
          type: "warning",
        })
        return
      }

      if (operateType == 'confirm') {
        // 确认订单
        if (this.ruleForm.refundMark == "平台退款中") {
          this.$confirm("平台退款中，是否要确认订单?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.confirmOrder();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取操作",
              });
            });
        } else {
          this.confirmOrder();
        }
      } else if (operateType == 'preservation') {
        // 保存信息
        if (this.orderStatus == 1) {
          this.ruleForm.status = 1;
          this.ruleForm.statusName = "未确认";
        }
        if (this.ruleForm.refundMark == "平台退款中") {
          this.$confirm("平台退款中，是否要修改订单信息?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.confirmUpdate();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消操作",
              });
            });
        } else {
          this.confirmUpdate();
        }
      } else if (operateType == 'refund' || operateType == 'return') {
        const ruleParams = this.getRuleFormParams()
        refundUnsubscribeConfirmOrder(ruleParams)
          .then((res) => {
            if (res.data.code == 200) {
              updateByProvisions(this.updateByProvisionsList).then(
                (res) => {
                  if (res.data.code == 200) {
                    if (this.UnsubscribeFlag) this.returnGoodsFlag = true;
                    if (this.refundFlag) this.refundOpenFlag = true;
                  }
                }
              );
            }
          })
          .catch((err) => {
            console.log(err);
            // alert(err)
          });
      }
    },
    validateParams({ isCheckBlessing = true, isCheckTime = true } = {}) {
      if (isCheckTime) {
        if (!this.getdeliveryStartTime || !this.$refs.getdeliveryTime || !this.$refs.getdeliveryTime.getStartTime()) {
          return '您还未选配送时间，请选择配送时间'
        }
        if (!this.isTimeOverCurrent(this.ruleForm.deliveryStartTime)) {
          return '该时间已过期，请重新选择'
        }
      }
      if (!this.shoplist || !this.shoplist.length) {
        return '你还未添加蛋糕，请添加蛋糕！'
      }
      if (!this.deptName) {
        return '您还未选城市，请选择城市'
      }
      if (!this.ruleForm.mainWarehouse || !this.ruleForm.branchWarehouse) {
        return '您还未选仓库，请选择仓库'
      }
      if (this.ruleForm.replaceDeliveryTime == 1) {
        return '请更换配送时间'
      }
      if (this.shoplist) {
        const unHasCake = this.shoplist.some(item => item.productionState == 6)
        if (unHasCake) {
          return '蛋糕中含有无货蛋糕，请联系用户更换蛋糕'
        }
        const unHasSpecs = this.shoplist.some(item => !item.goodsSpecs)
        if (unHasSpecs) {
          const noSpecsCakes = this.shoplist.filter(item => !item.goodsSpecs)
          return `蛋糕（${noSpecsCakes.map(item => item.goodsName).join(',')}）没有规格，请联系用户更换蛋糕`
        }
        const unHasSku = this.shoplist.some(item => !item.skuCode)
        if (unHasSku) {
          const noSkuCakes = this.shoplist.filter(item => !item.skuCode)
          return `蛋糕（${noSkuCakes.map(item => item.goodsName).join(',')}）sku码不能为空`
        }
        const isBlessingsOverLimit = this.shoplist.some(item => item.blessings && item.blessings.length > 32)
        if (isBlessingsOverLimit && isCheckBlessing) {
          const overLimitCakes = this.shoplist.filter(item => item.blessings && item.blessings.length > 32)
          return `蛋糕（${overLimitCakes.map(item => item.goodsName).join(',')}）祝福语超过32个字`
        }
      }
    },
    // 获取ruleForm参数
    getRuleFormParams() {
      const params = {
        ...this.ruleForm
      }
      if (this.showCustomMade) {
        const diyData = this.$refs.diyCakeInfo.getDiyData()
        params.diyCakeName = diyData.diyCakeName
        params.diyCakeNum = diyData.diyCakeNum
        params.diyCakeMeter = diyData.diyCakeMeter
      }
      if (this.ruleForm.longAndLat) {
        const location = this.ruleForm.longAndLat.split(',')
        params.longitude = location[0]
        params.latitude = location[1]
        delete params.longAndLat
      }
      return params
    },
    // 平台退款中（保存信息）
    confirmUpdate() {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) {return}
        this.validateIsCreateNewOrder().then(isSave => {
          if (isSave) {
            const ruleParams = this.getRuleFormParams()
            refundUnsubscribeConfirmOrder(ruleParams)
              .then((res) => {
                if (res.data.code == 200) {
                  updateByProvisions(this.updateByProvisionsList).then((res2) => {
                    if (res2.data.code == 200) {
                      this.$message({
                        type: "success",
                        message: "操作成功!",
                      });
                      window.localStorage.setItem("routerFlag", false);
                      if (res.data.data && res.data.data !== '0') {
                        this.$refs.updateWorkGoodsDialog.show({workOrderId: res.data.data, orderData: this.ruleForm, source: 2})
                      } else {
                        this.confirmTypeOrder();
                      }
                    }
                  });
                } else if (res.data.code == 300) {
                  this.$message({
                    type: "warning",
                    message: `${res.data.msg}`,
                  });
                } else if (res.data.code == 301) {
                  this.$message({
                    type: "warning",
                    message: `${res.data.msg}`,
                  });
                }
              })
              .catch((err) => {
                console.log(err);
                this.preservationFlag = false;
                // alert(err)
              });
          }
        })
      })
    },
    validateIsCreateNewOrder() {
      const statusMsg = {
        1: '生产中',
        2: '已入库',
        3: '配送中',
      }
      return new Promise(resolve => {
        validateOrder({
          id: this.ruleForm.id,
          warehouseId: this.ruleForm.warehouseId,
          deliveryStartTime: this.ruleForm.deliveryStartTime
        }).then(res => {
          const prodRes = res.data.data || {}
          if ([1,2,3].includes(prodRes.state)) {
            // 创建新订单
            this.$confirm(`订单${statusMsg[prodRes.state]}，请确认是否退订并创建新订单？`, {
              confirmButtonText: "是",
              cancelButtonText: "否",
              type: "warning",
              showClose: false, // 右上角关闭按钮
              closeOnClickModal: false, // 点击遮罩
              closeOnPressEscape: false, // 通过按下 ESC 键关闭
            }).then(res => {
              const params = this.getCreateOrderParams({logRemark: prodRes.msg})
              this.isConfirmCancelOrder = true
              clientAddWorkOrderUnsubscribe(params).then(res => {
                resolve(false)
                this.isConfirmCancelOrder = false
                this.confirmTypeOrder(`下单成功,单号${res.data.data}`);
              })
            }).catch(() => {
              const params = {
                orderId: this.ruleForm.id,
                type: this.ruleForm.status,
                action: `订单发生变更，未建新单`,
                orderType: 1,
                workType: 0,
              }
              add0rderOperateLog(params)
              resolve(true)
            })
          } else {
            resolve(true)
          }
        })
      })
    },
    getCreateOrderParams(customParams) {
      const params = {
        "id": this.ruleForm.id,
        "receiverAddress": this.ruleForm.receiverAddress,
        "receiverName": this.ruleForm.receiverName,
        "receiverPhone": this.ruleForm.receiverPhone,
        "orderTime": this.ruleForm.orderTime,
        "channel": this.ruleForm.channel,
        "mainWarehouse": this.ruleForm.mainWarehouse,
        "branchWarehouse": this.ruleForm.branchWarehouse,
        "deptId": this.ruleForm.deptId,
        "customerNotes": this.ruleForm.customerNotes,
        "productionNotes": this.ruleForm.productionNotes,
        "deliveryNotes": this.ruleForm.deliveryNotes,
        "deliveryStartTime": this.ruleForm.deliveryStartTime,
        "deliveryEndTime": this.ruleForm.deliveryEndTime,
        "longitude": this.ruleForm.longitude,
        "latitude": this.ruleForm.latitude,
        "mainWarehouseId": this.ruleForm.mainWarehouseId,
        "warehouseId": this.ruleForm.warehouseId,
        "platformOrderId": this.ruleForm.platformOrderId,
        "channelType": this.ruleForm.channelType,
        "customerServiceNotes": this.ruleForm.customerServiceNotes,
        "storeInfo": this.ruleForm.storeInfo,
        "totalPrice": this.ruleForm.totalPrice,
        "isDance": this.ruleForm.isDance,
        "bookerName": this.ruleForm.bookerName,
        "bookerPhone": this.ruleForm.bookerPhone,
        "merchantName": this.ruleForm.merchantName,
        "partsList": this.ruleForm.orderDetailRequests.filter(item => item.goodsTypeName == '配件' || item.goodsTypeName == '增值服务'),
        "serviceClassList": this.ruleForm.orderDetailRequests.filter(item => item.goodsTypeName == '服务费'),
        "customizedOrderDetailList": this.ruleForm.orderDetailRequests.filter(item => item.goodsTypeName == '定制蛋糕'),
        "orderDetailList": this.ruleForm.orderDetailRequests.filter(item => {
          return ['配件', '服务费', '定制蛋糕', '增值服务'].every(name => name != item.goodsTypeName)
        }),
        "workOrderProvisionsList": [],
        "merchantId": this.ruleForm.merchantId,
        ...customParams
      }
      return params
    },
    // 确认订单请求
    confirmOrder() {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) {return}
        const ruleParams = this.getRuleFormParams()
        updateList(ruleParams)
          .then((res) => {
            if (res.data.code == 200) {
              updateByProvisions(this.updateByProvisionsList).then((res2) => {
                if (res2.data.code == 200) {
                  this.$message({
                    type: "success",
                    message: "操作成功!",
                  });
                  window.localStorage.setItem("routerFlag", true);
                  if (res.data.data && res.data.data !== '0') {
                    this.$refs.updateWorkGoodsDialog.show({workOrderId: res.data.data, orderData: this.ruleForm, source: 3})
                  } else {
                    this.confirmTypeOrder();
                  }
                }
              });
            } else if (res.data.code == 300) {
              this.$message({
                type: "warning",
                message: `${res.data.msg}`,
              });
            } else if (res.data.code == 301) {
              this.$message({
                type: "warning",
                message: `${res.data.msg}`,
              });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      })
    },
    // 确认订单、保存信息二次确认
    confirmTypeOrder(customMessage) {
      this.$confirm(
        customMessage || (this.preservationFlag == false
          ? `下单成功,单号${this.ruleForm.xmbzNo}`
          : `保存成功,单号${this.ruleForm.xmbzNo}`),
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          showCancelButton: false, // 取消按钮
          showClose: false, // 右上角关闭按钮
          closeOnClickModal: false, // 点击遮罩
          closeOnPressEscape: false, // 通过按下 ESC 键关闭
          customClass: "timeNumbers",
        }
      ).then(() => {
        window.close();
      });
      document.onkeydown = function (e) {
        //按下回车弹窗消失
        let key = window.event.keyCode;
        //事件中keycode=13为回车事件
        if (key == 13) {
          window.close();
        }
      };
    },
    // 取消确认订单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 判断订单配送时间是否小于当前时间
    isTimeOverCurrent(timeval) {
      const current = new Date()
      const time = new Date(timeval)
      return time.getTime() > current.getTime()
    },
    // 地图事件
    SearchAddress() {
      this.addressFlagcopy = true;
      inputTipThrottle({
        city: this.deptName,
        keyword: this.receiverDetailAddress
      }).then(res => {
        this.addressList = res.map(item => {
          return {
            ...item,
            lng: item.location && item.location.lng,
            lat: item.location && item.location.lat,
          }
        }).sort((a, b) => {
          return a.district.includes(this.ruleForm.deptName) && !b.district.includes(this.ruleForm.deptName) ? -1 : 0
        })
      })
    },
    // 点击地图的列表获取经纬度
    getlnglat(index) {
      this.addressFlagcopy = false;
      index = (this.currentPage - 1) * this.pagesize + index;
      if (typeof index === "string") index = 0;
      let pois = this.addressList[index];
      if (pois.lat) {
        // console.log('ooooooooooooo')
        this.getWarehouseName.latitude = pois.lat;
        this.getWarehouseName.longitude = pois.lng;
        this.latitude = pois.lat;
        this.longitude = pois.lng;
        getWarehouseName(this.getWarehouseName).then((res) => {
          if (res.data.msg == "操作成功") {
            this.getSeparateWarehouseList.deptId = res.data.data.deptId;
            this.ruleForm.mainWarehouseId = res.data.data.deptId;
            this.deptName = res.data.data.cityName;
            this.ruleForm.deptId = res.data.data.cityId; ////////
            this.ruleForm.mainWarehouse = res.data.data.deptName; ///////
            this.ruleForm.warehouseId = res.data.data.id; /////////
            this.ruleForm.branchWarehouse = res.data.data.name; ////////
            this.judgeGoodsClose()
            if (typeof this.getSeparateWarehouseList.deptId === "number") {
              getSeparateWarehouseList(this.getSeparateWarehouseList).then(
                (res) => {
                  this.abbrlist = res.data.data;
                }
              );
            }
            if (this.deptId == res.data.data.cityId) {
              // console.log('res.data.data没有更换城市',res.data.data)
              // this.ruleForm.receiverAddress = pois.name;
              this.receiverDetailAddress = pois.name;
              this.ruleForm.latitude = pois.lat;
              this.ruleForm.longitude = pois.lng;
              this.latitudeFlag = "initialcity";
              this.startArea(res.data.data.cityId);
              this.handleMapData();
            } else {
              // console.log('this.deptId',this.deptId)
              this.$confirm("已修改配送城市，是否继续？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.latitudeFlag = true;
                  this.ruleForm.deptName = res.data.data.cityName;
                  // this.ruleForm.receiverAddress = pois.name;
                  this.receiverDetailAddress = pois.name;
                  this.ruleForm.latitude = pois.lat;
                  this.ruleForm.longitude = pois.lng;
                  this.startArea(res.data.data.cityId);
                  this.handleMapData();
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消选择地址",
                  });
                });
            }
          } else if (res.data.msg == "暂无承载数据") {
            this.$confirm(
              "您选择的地址不在配送范围内, 请联系用户！",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(() => {
                // this.ruleForm.receiverAddress = pois.name;
                this.receiverDetailAddress = pois.name;
                this.ruleForm.latitude = pois.lat;
                this.ruleForm.longitude = pois.lng;
                this.startArea(this.ruleForm.deptId || 1);
                this.handleMapData();
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消选择地址",
                });
              });
          }
          // console.log('res.data.data',res.data.data)
        });
      } else {
        this.$confirm("此地址不存在, 请重新选址！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$message({
              type: "warning",
              message: "请继续选择地址!",
            });
            // this.ruleForm.receiverAddress = ''
            this.receiverDetailAddress = "";
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消选择地址",
            });
          });
      }
    },
    //方向键（向上）
    selectTopItem() {
      if (this.addressList.length > 0 && this.addressList.length <= 5) {
        if (
          this.currentIndex >= 0 &&
          this.currentIndex < this.addressList.length - 1
        ) {
          this.currentIndex--;
        } else {
          this.currentIndex = 0;
        }
        // console.log('上',this.currentIndex)
      } else {
        if (
          this.currentIndex >= 0 &&
          this.currentIndex < this.addressList.length - 1
        ) {
          this.currentIndex--;
        } else {
          this.currentIndex = 0;
        }
      }
    },
    //方向键（向下）
    selectBottomItem(index) {
      if (this.addressList.length > 0 && this.addressList.length <= 5) {
        if (
          this.currentIndex >= 0 &&
          this.currentIndex < this.addressList.length - 1
        ) {
          this.currentIndex++;
        } else {
          this.currentIndex = 0;
        }
      } else {
        // console.log('2',this.currentIndex >= 0 && this.currentIndex < this.addressList.length - 1)
        if (
          this.currentIndex >= 0 &&
          this.currentIndex < this.addressList.length - 1
        ) {
          this.currentIndex++;
        } else {
          this.currentIndex = 0;
        }
      }
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.pagesize = size;
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage;
    },
    // 划过列表颜色改变
    changeColor(index) {
      this.currentIndex = index;
    },
    // 离开列表颜色改变
    loseColor(index) {
      this.currentIndex = index;
    },
    // 选择渠道类型
    getchannelTypeId(e) {
      // console.log('e.currentTarget.dataset',e.currentTarget.dataset)
      this.ruleForm.channelType = e.currentTarget.dataset.channeltype;
      this.getChannelList.parentId = e.currentTarget.dataset.id;
      // 渠道列表接口
      getOrderChannelList(this.getChannelList).then((res) => {
        let result = res.data.data;
        result.forEach((item) => {
          if (item.channelKey == this.ruleForm.channel) {
            // console.log('有',item)
            this.channerllist = result;
          } else {
            this.channerllist = result;
            this.ruleForm.channel = "";
            this.ruleForm.channelName = "";
          }
        });
      });
    },
    // 下单仓库城市总仓获取
    getMainWarehouse(deptId) {
      // console.log('result',deptId)
      this.getMainWarehouseList.parentId = deptId;
      // 总仓
      if (this.getMainWarehouseList.parentId !== 1) {
        getMainWarehouseList(this.getMainWarehouseList).then((res) => {
          let result = res.data.data;
          // console.log('result',result)
          this.citylist = result;
          this.changeselectBtn(result);
          // console.log('this.citylist',this.citylist)
          result.forEach((item) => {
            if (this.ruleForm.mainWarehouse == item.deptName) {
              this.citylist = result;
              // 对应总仓的分仓
              getSeparateWarehouseList({ deptId: item.id }).then((res) => {
                this.abbrlist = res.data.data;
              });
            }
          });
        });
      }
    },
    // 下单分仓获取
    wareclick(e) {
      console.log(e.currentTarget.dataset.id);
      // console.log('wareclick',e.currentTarget.dataset)
      this.getSeparateWarehouseList.deptId = e.currentTarget.dataset.id;
      this.ruleForm.mainWarehouseId = Number(e.currentTarget.dataset.id);
      getSeparateWarehouseList(this.getSeparateWarehouseList).then((res) => {
        let abbrResult = res.data.data;
        // console.log('abbrResult',abbrResult.length)
        if (abbrResult.length > 0) {
          abbrResult.forEach((item) => {
            if (item.name == this.ruleForm.branchWarehouse) {
              this.ruleForm.branchWarehouse = item.name;
              this.abbrlist = abbrResult;
            } else if (item.name !== this.ruleForm.branchWarehouse) {
              this.abbrlist = abbrResult;
              this.ruleForm.branchWarehouse = "";
            }
          });
        } else {
          this.abbrlist = abbrResult;
          // console.log('this.abbrlist03',abbrResult)
          this.ruleForm.branchWarehouse = "";
        }
      });
      // console.log('this.ruleForm',this.ruleForm)
    },
    getwareHouseOpen(val) {
      // 获取区(即总仓)ruleForm
      // console.log(val,'val')
      // this.ruleForm.mainWarehouse = val
      this.ruleForm.mainWarehouse = val;
    },
    
    // 退订弹窗打开
    returnGoodsOpen() {
      this.selectArray = [];
      this.shoplist.forEach((item) => {
        if (item.goodsTypeName != "服务费") {
          this.selectArray.push(item.id);
        }
      });
      if (this.ruleForm.status == 1) {
        this.refundFlag = false;
        this.UnsubscribeFlag = true;
        this.preservationFlag = false;
        // this.statusUpdate({operateType: 'return'});
        this.returnGoodsFlag = true;
      } else if (this.ruleForm.status > 1) {
        this.UnsubscribeFlag = false;
        this.returnGoodsFlag = true;
        this.preservationFlag = false;
      }
    },
    handleCheckedCitiesChange(e) {
      console.log("e", e.currentTarget);
    },
    // 退订确认按钮
    unsubscribeSubmitForm(e, formName) {
      this.unsubscribeForm.noSelectOrderDetailIds = [];
      this.unsubscribeForm.noSelectOrderDetailIds = this.selectArray;
      this.unsubscribeForm.selectOrderDetailIds = this.unsubscribeForm.orderDetailIds;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.unsubscribeForm.selectOrderDetailIds.length > 0) {
            this.unsubscribeForm.orderId = e.currentTarget.dataset.id;
            addWorkOrderUnsubscribe(this.unsubscribeForm)
              .then((res) => {
                if (res.data.code == 200) {
                  this.$refs[formName].resetFields();
                  this.returnGoodsFlag = false;
                  this.UnsubscribeFlag = false;
                  this.PlaRefundQuery(this.unsubscribeForm.selectOrderDetailIds); // 平台退款中标记消失
                  this.$confirm(
                    `退订成功！后台单号：${this.ruleForm.xmbzNo}`,
                    "提示",
                    {
                      showCancelButton: false,
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "success",
                    }
                  )
                    .then(() => {
                      window.close();
                      // window.opener.location.reload();
                    })
                    .catch(() => {});
                }
              })
              .catch((err) => {
                this.$refs[formName].resetFields();
                this.returnGoodsFlag = false;
              });
          } else {
            this.$message({
              showClose: true,
              message: "退订发起失败，请选择商品",
              type: "warning",
            });
          }
        } else {
          return false;
        }
      });
    },
    unsubscribeFormClose() {
      this.$confirm("确认关闭？")
        .then(() => {
          this.$refs["unsubscribeForm"].resetFields();
          this.UnsubscribeFlag = false;
          this.returnGoodsFlag = false;
        })
        .catch(() => {});
    },
    unsubscribeResetForm(formName) {
      // 退订取消按钮
      this.$refs[formName].resetFields();
      this.UnsubscribeFlag = false;
      this.returnGoodsFlag = false;
    },
    // 退款界面显示
    async refundOpen() {
      const replaceRes = await validateReplacementOrder({orderId: this.ruleForm.id})
      if (replaceRes.data && replaceRes.data.code == 200) {
        this.resetRefundForm();
        // this.refundForm.refundMoney = this.refundCakePrice = 0;
        this.RefundShowFlag = true;
        this.RefundNoReShowFlag = false;
        this.getQueryList();
      } else{
        this.$message.error('操作异常，请重试！')
      }
    },
    // 退款不退货界面显示
    async RefundNoRe() {
      const replaceRes = await validateReplacementOrder({orderId: this.ruleForm.id})
      if (replaceRes.data && replaceRes.data.code == 200) {
        this.resetRefundForm();
        this.RefundNoReShowFlag = true;
        this.RefundShowFlag = false;
        this.getQueryList();
      } else {
        this.$message.error('操作异常，请重试！')
      }
    },
    getRefundList() {
      getGoodsByOrderId({ orderId: this.ruleForm.id }).then((res) => {
        this.refundList = res.data.data;
      });
    },
    // 退款界面打开所需请求的接口、商品类型显隐判断
    getQueryList() {
      this.shoplist.forEach((item) => {
        if (item.goodsTypeName != "服务费") {
          this.selectArray.push(item.id);
        }
      });
      if (this.ruleForm.status == 1) {
        this.UnsubscribeFlag = false;
        this.refundFlag = true;
        this.preservationFlag = false;
        // this.statusUpdate({operateType: 'refund'});
        this.refundOpenFlag = true;
      } else if (this.ruleForm.status > 1) {
        this.refundOpenFlag = true;
        this.preservationFlag = false;
        this.refundFlag = false;
      }
      getRefundModeList().then((res) => {
        // console.log('待生产','待生产',res)
        this.radioList = res.data.data;
      });
      // 退款等级列表getRefundGradeList
      getRefundGradeList().then((res) => {
        // console.log(res)
        this.getRefundGradeList = res.data.data;
      });
      this.getRefundTypeReasonList()
      
      getCompensationMethodList().then((res) => {
        // 赔偿方式列表
        this.getCompensationMethodList = res.data.data;
      });

      this.getRefundList(); // 商品
      this.getTyingSaleTypeList(); // 搭售类型
      this.getListTyingSaleProducts(); // 搭售商品
    },
    // 主图开始上传
    handleAvatarSuccess(response, file, fileList) {
      console.log('response'+'::>>', response)
      this.temp.mainPic = response.data;
      this.refundForm.refundCode = fileList[fileList.length - 1].response.data;
      // console.log('handleAvatarSuccess',this.refundForm.refundCode,fileList[0].response)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }, // 图片预览及删除
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    fileChange(file) {
      this.$refs.upload.clearFiles(); //清除文件对象
      this.logo = file.raw; // 取出上传文件的对象，在其它地方也可以使用
      this.fileList = [{ name: file.name, url: file.url }]; // 重新手动赋值filstList， 免得自定义上传成功了, 而fileList并没有动态改变， 这样每次都是上传一个对象
    },
    compensationMethodOpen(val) {
      console.log(val);
    },
    // 退款，赔偿
    getRadio(val) {
      if (val == 1) {
        // this.refundForm.refundMoney = this.refundCakePrice
        this.refundRadioFlag = true;
        this.payforRadioFlag = false;
        this.compensationMethodFlag = false;
        this.refundForm.cakeCompensatePrice = "";
        this.refundForm.sincerityGold = 0;
        this.refundForm.giveCakePrice = 0;
        this.refundForm.giveGiftPrice = 0;
      } else {
        this.refundForm.cakeCompensatePrice = 0;
        // this.refundForm.refundMoney = ''
        this.payforRadioFlag = true;
        this.refundRadioFlag = false;
        this.compensationMethodFlag = true;
        this.refundForm.compensationMethod = 6;
      }
    },
    // 赔偿方式
    getcompensationMethodRadio(val) {
      if (val == 6) {// 无赔偿
        this.compensationMethodFlag = true;
        this.refundForm.cakeCompensatePrice = 0;
        // this.refundForm.refundMoney = 0
      } else if (val == 1) {// 免单
        this.refundForm.refundMoney = 0;
        this.compensationMethodFlag = true;
        this.refundForm.cakeCompensatePrice = this.refundCakePrice;
      } else if (val == 2) {// 免半单
        this.refundForm.refundMoney = 0;
        this.compensationMethodFlag = true;
        this.refundForm.cakeCompensatePrice = this.refundCakePrice / 2;
      }
    },
    // 退款模块获取蛋糕价格
    getTotalprice() {
      this.getrefundAmount();
    },
    // 退款模块获取定制蛋糕价格
    getCustomprice() {
      this.getrefundAmount();
    },
    // 退款模块获取配件价格
    getPartsprice() {
      this.getrefundAmount();
    },
    // 获取退款不同商品类型的蛋糕的价格
    getrefundAmount() {
      if (this.refundForm.selectOrderDetailIds && this.refundForm.selectOrderDetailIds.length > 0) {
        let cakePrice = [];
        let cakeSumPrice = 0;
        this.refundForm.selectOrderDetailIds.forEach((item, valueindex) => {
          this.shoplist.forEach((shopitem, shopindex) => {
            if (item == shopitem.id) {
              cakePrice.push(this.shoplist[shopindex].totalPrice);
            }
          });
        });
        cakePrice.forEach((item, priceindex) => {
          cakeSumPrice += cakePrice[priceindex];
        });
        this.refundCakePrice = cakeSumPrice / 100;
        // this.refundForm.refundMoney = this.refundCakePrice
        if (this.refundForm.compensationMethod == 6) {
          this.refundForm.cakeCompensatePrice = 0;
        } else if (this.refundForm.compensationMethod == 1) {
          this.refundForm.cakeCompensatePrice = this.refundCakePrice;
        } else if (this.refundForm.compensationMethod == 2) {
          this.refundForm.cakeCompensatePrice = this.refundCakePrice / 2;
        }
      } else {
        this.refundCakePrice = 0.0;
        // this.refundForm.refundMoney = this.refundCakePrice;
        if (this.refundForm.compensationMethod == 6) {
          this.refundForm.cakeCompensatePrice = 0;
        } else if (this.refundForm.compensationMethod == 1) {
          this.refundForm.cakeCompensatePrice = this.refundCakePrice;
        } else if (this.refundForm.compensationMethod == 2) {
          this.refundForm.cakeCompensatePrice = this.refundCakePrice / 2;
        }
      }
    },
    refundFormClose() {
      // 关闭退款弹窗
      this.$confirm("确认关闭？")
        .then(() => {
          this.refundOpenFlag = false;
          this.refundFlag = false;
        })
        .catch(() => {});
    },
    getRefundFormParams() {
      const obj = JSON.parse(JSON.stringify(this.refundForm))
      const selectItem = this.getRefundReasonList.find(item => item.value === this.refundForm.refundReason)
      if (selectItem) {
        obj.refundType = selectItem.typeKey
      }
      if (this.isTyingRefund) {
        // 搭售退款
        obj.tyingSales = obj.tyingSales.map(orderDetailId => {
          const item = this.refundTyingList.find(item => item.id == orderDetailId)
          return {
            orderDetail: orderDetailId,
            goodsName: item.goodsName,
            tyingSaleName: item.tyingCheckeds.join(','),
          }
        })
        obj.selectOrderDetailIds = []
      } else {
        obj.tyingSales = []
      }
      obj.refundTypeName = this.refundForm.refundType
      return obj
    },
    // 多次提交退款
    handleRefundAgain(detail) {
      this.$refs.againRefundDialog.show({
        detail,
        order: this.ruleForm,
        type: this.RefundShowFlag ? 0 : 1
      })
    },
    showAgainRefundBtn(detail) {
      return detail.refundIdentification === '已退款' && detail.workRefundId != '-1' && detail.whetherRefund == 1
    },
    // 退款确认按钮
    refundSubmitForm(e, formName) {
      this.refundForm.noSelectOrderDetailIds = this.selectArray || [];
      this.refundForm.orderId = this.ruleForm.id;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const otherValid = this.validateRefundForm()
          if (otherValid) {
            if (this.RefundShowFlag) {
              // 退款
              this.addWorkOrderRefund()
            } else if (this.RefundNoReShowFlag) {
              // 退款不退货
              this.addRefundNotReturn()
            }
          }
        } else {
          this.$message({
            message: "信息未填完整",
            type: "warning",
          });
          return false;
        }
      });
    },
    validateRefundForm() {
      let errorMsg = ''
      if (this.isTyingRefund) {
        const checkeds = this.refundForm.tyingSales.map(item => {
          return this.refundTyingList.find(l => l.id == item)
        })
        if (checkeds.length == 0 || checkeds.some(item => item.tyingCheckeds.length == 0)) {
          errorMsg = '请选择退货的搭售商品'
        }
      } else {
        if (!this.refundForm.selectOrderDetailIds || !this.refundForm.selectOrderDetailIds.length ) {
          errorMsg = '退款发起失败，请选择商品'
        }
      }
      if (errorMsg) {
        this.$message({
          showClose: true,
          message: errorMsg,
          type: "warning",
        });
        return false
      } else {
        return true
      }
    },
    // 退款
    addWorkOrderRefund() {
      const params = this.getRefundFormParams()
      addWorkOrderRefund(params).then(res => {
        if (res.data.code == 200) {
          this.refundOpenFlag = false;
          this.refundFlag = false;
          this.PlaRefundQuery(params.selectOrderDetailIds); // 平台退款中标记消失
          this.$confirm(
            `退款成功！后台单号：${this.ruleForm.xmbzNo}`,
            "提示",
            {
              showCancelButton: false,
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "success",
            }).then(() => {
              window.close();
            })
        }
      })
    },
    // 退款不退货
    addRefundNotReturn() {
      const params = this.getRefundFormParams()
      addRefundNotReturn(params).then(res => {
        if (res.data.code == 200) {
          this.refundOpenFlag = false;
          this.refundFlag = false;
          this.PlaRefundQuery(params.selectOrderDetailIds); // 平台退款中标记消失
          this.$confirm(
            `退款成功！后台单号：${this.ruleForm.xmbzNo}`,
            "提示",
            {
              showCancelButton: false,
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "success",
            }).then(() => {
              window.close();
            })
        }
      })
    },
    resetRefundForm() {
      this.$refs['refundForm'] && this.$refs['refundForm'].resetFields();
      this.refundForm.orderId = "";
      this.refundForm.refundCode = "";
      this.temp.mainPic = "";
      this.refundForm.compensationMethod = "";
      this.refundForm.selectOrderDetailIds = [];
      this.refundForm.tyingSales = [];
      this.refundForm.refundWay = '1';
      this.selectArray = [];
      this.refundForm.sincerityGold = 0;
      this.refundForm.giveCakePrice = 0;
      this.refundForm.giveGiftPrice = 0;
      this.refundForm.cakeCompensatePrice = 0;
    },
    // 退款取消按钮
    refundResetForm() {
      this.refundOpenFlag = false;
      this.refundFlag = false;
    },
    // 恢复订单
    recoverOpen() {
      this.recoverOrderFlag = true;
    },
    recoverSubmitForm(e, formName) {
      this.recoverForm.orderId = e.currentTarget.dataset.id;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          getRecoveryOrder(this.recoverForm).then((res) => {
            if (res.data.code == 200) {
              this.$notify({
                title: "恢复订单成功",
                message: "请您耐心等待",
                type: "success",
              });
              this.$refs[formName].resetFields();
            }
          });
        } else {
          return false;
        }
      });
    },
    recoverResetForm(formName) {
      this.$refs[formName].resetFields();
      this.recoverOrderFlag = false;
    },
    reminderOpen() {
      this.$refs.remindDialog.show();
    },
    // 备款
    frmLossOpen() {
      this.frmLossFlag = true;
      this.selectArray = [];
      this.shoplist.forEach((item) => {
        if (item.goodsTypeName != "服务费") {
          this.selectArray.push(item.id);
        }
      });
      // 备款责任部门
      getResponsibleDepartmentList().then((res) => {
        this.frmLossList = res.data.data;
      });
      // 备款来源
      getProvisionsOperationList().then((res) => {
        // console.log(res.data.data)
        this.getSourceList = res.data.data;
      });
    },
    idProvisionsOperation() {
      if (this.frmLossForm.provisionsOperation == 1) {
        this.refundCakeFlag = true;
        this.frmLossTimeFlag = false;
      } else if (this.frmLossForm.provisionsOperation == 2) {
        this.refundCakeFlag = false;
        this.frmLossTimeFlag = true;
      }
    },
    frmLossSubmitForm(e, formName) {
      // 备款确认按钮
      // // console.log('配水间',goodsId,'定制单狗')
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log("this.frmLossForm.unsubscribeReason",this.frmLossForm.unsubscribeReason)
          const frmLossCancelForm = {
            // 备款退订请求参数
            orderId: e.currentTarget.dataset.id, //后台单号
            orderDetailIds: this.frmLossForm.orderDetailIds, //详情id
            personDept: this.frmLossForm.personDept, //部门
            personLiable: this.frmLossForm.personLiable, //责任人
            cakeWhereabouts: this.frmLossForm.cakeWhereabouts, //蛋糕去向
            provisionsContent: this.frmLossForm.provisionsContent, //备款内容
            provisionsOperation: this.frmLossForm.provisionsOperation, //备款来源
            isProduction: this.frmLossForm.isProduction, // 是否生产
            applyReason: this.frmLossForm.applyReason, // 申请原因
            unsubscribeReason: this.frmLossForm.unsubscribeReason, // 退订原因
          };
          this.frmLossForm.orderId = e.currentTarget.dataset.id;
          if (this.frmLossForm.provisionsOperation == 1) {
            if (!this.frmLossForm.orderDetailIds || !this.frmLossForm.orderDetailIds.length) {
              this.$message({
                message: "备款蛋糕不能为空",
                type: "warning",
              });
              return
            }
            if (!this.frmLossForm.unsubscribeReason) {
              this.$message({
                message: "退订原因不能为空",
                type: "warning",
              });
              return
            }
            if (!this.frmLossForm.applyReason) {
              this.$message({
                message: "申请原因不能为空",
                type: "warning",
              });
              return
            }
            addWorkOrderProvisions(frmLossCancelForm)
              .then((res) => {
                if (res.data.code == 200) {
                  this.frmLossForm.unsubscribeReason = "";
                  this.frmLossForm.applyReason = "";
                  this.frmLossForm.orderDetailIds = "";
                  this.$refs[formName].resetFields();
                  this.frmLossFlag = false;
                  this.PlaRefundQuery(frmLossCancelForm.orderDetailIds); // 平台退款中标记消失
                  this.$confirm(
                    `备款成功！后台单号：${this.ruleForm.xmbzNo}`,
                    "提示",
                    {
                      showCancelButton: false,
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      center: true,
                      type: "success",
                    }
                  )
                    .then(() => {
                      window.close();
                      // window.opener.location.reload();
                    })
                    .catch(() => {});
                  // console.log('1')
                }
              })
              .catch((err) => {
                console.log(err);
              });
          } else if (this.frmLossForm.provisionsOperation == 2) {
            if (
              this.$refs.getdeliveryTime !== undefined &&
              this.$refs.getdeliveryTime.getStartTime() !== "" &&
              this.$refs.getdeliveryTime.getEndTime() !== ""
            ) {
              this.frmLossForm.distributionStartTime =
                this.$refs.getdeliveryTime.deliveryTime +
                this.$refs.getdeliveryTime.getStartTime();
              this.frmLossForm.distributionEndTime =
                this.$refs.getdeliveryTime.deliveryTime +
                this.$refs.getdeliveryTime.getEndTime();
              this.frmLossForm.orderDetailIds = this.shoplist.filter(item => item.goodsTypeName == "蛋糕").map(item => item.id)
              const getDeliveryFlag = this.isTimeOverCurrent(this.frmLossForm.distributionStartTime);
              if (getDeliveryFlag) {
                addWorkOrderProvisions(this.frmLossForm).then((res) => {
                  if (res.data.code == 200) {
                    this.$confirm(
                      `<div style="text-align: left;margin-left: 8px;">备款成功！后台单号：${this.ruleForm.xmbzNo}</div><br/><div style="text-align: left;margin-left: 8px;">${res.data.data}</div>`,
                      "提示",
                      {
                        showCancelButton: false,
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        dangerouslyUseHTMLString: true,
                        center: true,
                        type: "success",
                      }
                    )
                      .then(() => {
                        window.close();
                        // window.opener.location.reload();
                      })
                      .catch(() => {});
                    this.frmLossForm.distributionStartTime = "";
                    this.frmLossForm.distributionEndTime = "";
                    this.frmLossForm.orderDetailIds = "";
                    this.$refs[formName].resetFields();
                    this.frmLossFlag = false;
                    this.PlaRefundQuery(); // 平台退款中标记消失
                    // console.log('2')
                  }
                });
              } else {
                this.$message.warning("该时间已过期，请重新选择");
              }
            } else {
              this.$alert(`您还未选配送时间，请选择配送时间`, "提示", {
                confirmButtonText: "确定",
                callback: (action) => {
                  this.$message({
                    type: "warning",
                    message: `请继续选择配送时间`,
                  });
                },
              });
            }
          }
        } else {
          return false;
        }
      });
    },
    frmLossResetForm(formName) {
      // 备款取消按钮
      this.$refs[formName].resetFields();
      this.frmLossFlag = false;
    },
    // 投诉
    complainOpen() {
      this.$refs.complainDialog.show({orderData: this.ruleForm})
    },
    openEditCake() {
      if (!this.ruleForm.branchWarehouse) {
        this.$message({
          message: "您还未选择仓库，请选择仓库后再添加蛋糕",
          type: "warning",
        });
        return
      }
      this.$refs.editGoodsDialog.show({shoplist: this.shoplist})
    },
    // 蛋糕提交
    handleGoodsSumbit({shoplist, sumPrice}) {
      this.shoplist = shoplist || [];
      this.ruleForm.sumPrice = (sumPrice / 100).toFixed(2);
      if (shoplist.length == 0) {
        this.ruleForm.orderDetailRequests = [];
      }
      let orderSubmitGoodsTimeQuery = {
        orderId: this.ruleForm.id,
        orderStatus: this.ruleForm.status,
        orderType: 1,
        workType: 0,
      };
      orderSubmitGoodsTime(orderSubmitGoodsTimeQuery)
        .then((res) => {
          console.log("res", res.data);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 商品类型列表
    getCategories() {
      getCategories("").then((res) => {
        const batchdata = res.data.data;
        const dataValueBatch = (batchdata) =>
          batchdata.map(({ id, categoryName, children }) =>
            children
              ? {
                  value: id,
                  label: categoryName,
                  disabled: categoryName == "未知分组" ? true : false,
                  children: dataValueBatch(children),
                }
              : {
                  value: id,
                  label: categoryName,
                }
          );
        this.getCategoriesList = dataValueBatch(batchdata);
        // console.log('getCategoriesList',this.getCategoriesList)
      });
    },
    //选择蛋糕类型
    selectCategory(selected, index) {
      // this.ruleForm.goodsTypeName = selected;
      this.getCategoriesList.forEach((item) => {
        // console.log('item',item)
        if (selected[0] == item.value) {
          // console.log('selected[0]',selected[0],selected[1],item.label,index)
          this.shoplist[index].parentCategoryId = selected[0];
          this.shoplist[index].categoryId = selected[1];
          this.shoplist[index].goodsTypeName = item.label;
        }
      });
    },
    // 备注空格问题
    filterSpace(data) {
      if (data === "customerNotes") {
        this.ruleForm.customerNotes = this.ruleForm.customerNotes.replace(
          /^\s+|\s+$/g,
          ""
        );
      } else if (data === "productionNotes") {
        this.ruleForm.productionNotes = this.ruleForm.productionNotes.replace(
          /^\s+|\s+$/g,
          ""
        );
      } else if (data === "deliveryNotes") {
        this.ruleForm.deliveryNotes = this.ruleForm.deliveryNotes.replace(
          /^\s+|\s+$/g,
          ""
        );
      } else if (data === "customerServiceNotes") {
        this.ruleForm.customerServiceNotes =
          this.ruleForm.customerServiceNotes.replace(/^\s+|\s+$/g, "");
      }
    },
    imgclick() {
      this.imgFlag = true;
    },
    // 平台退款中按钮请求
    PlaRefund() {
      this.$confirm("是否确认取消平台退款?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {
            orderId: this.ruleForm.id,
            type: 1,
          };
          deleteOrderExt(params)
            .then((res) => {
              this.$message.success("已取消平台退款");
              window.localStorage.setItem("routerFlag", true);
              setTimeout(() => {
                window.close();
              }, 1.5 * 1000);
            })
        })
    },
    // 平台退款请求
    PlaRefundQuery(orderDetailIds) {
      let params = {
        orderId: this.ruleForm.id,
        orderDetailIds,
        type: 2,
      };
      if (this.ruleForm.refundMark == "平台退款中") {
        deleteOrderExt(params)
      }
    },
    // 电话号码限制
    filterPhone(val) {
      // console.log('va',val)
      this.ruleForm.receiverPhone = val.replace(/[^\d]/g, "");
    },
    overTimeOrder() {
      let isNotice = false
      this.detailtimer = setInterval(() => {
        this.timeNumbers += 300;
        if (this.timeNumbers > 0 && this.timeNumbers % 300 == 0 && !isNotice) {
          isNotice = true
          this.$confirm(`你锁住此订单已经超过${this.timeNumbers / 60}分钟`, "提示", {
            confirmButtonText: "确定",
            type: "warning",
            showCancelButton: false, // 取消按钮
            showClose: false, // 右上角关闭按钮
            closeOnClickModal: false, // 点击遮罩
            closeOnPressEscape: false, // 通过按下 ESC 键关闭
            customClass: "timeNumbers",
          }).then(() => {
            isNotice = false
          });
        }
      }, 300 * 1000);
      document.onkeydown = function (e) {
        //按下回车弹窗消失
        let key = window.event.keyCode;
        //事件中keycode=13为回车事件
        if (key == 13) {
          const clickBtn = document.querySelector('.timeNumbers .el-button')
          clickBtn && clickBtn.click();
        }
      };
    },
    //打标
    labelOpen() {
      this.$refs.setLabelDialog.show()
    },
    // 转接客服
    transToCustomerS() {
      if (this.ruleForm && this.ruleForm.staffForward === "客服转接") {
        this.$confirm("是否确认取消退款挽留吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          const param = {
            orderId: this.orderId,
            isForward: 0, // 取消转接
          };
          staffForward(param).then((res) => {
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: "取消成功",
              });
              this.ruleForm.staffForward = ''
            } else {
              this.$message({
                type: "error",
                message: res.data.msg,
              });
            }
          });
        });
      } else {
        this.$refs.reasonDialog.show({
          order: this.ruleForm
        });
      }
    },
    
    
    // 点击地址搜索框以外
    onClickSearchOutside() {
      this.addressFlagcopy = false
    },
    // 咨询快乐
    handleConsultHappy() {
      this.$refs.addConsultHappyDialog.show({ type: 'add', orderData: this.ruleForm })
    },
    // 搭售类型
    getTyingSaleTypeList() {
      getCacheData('tying_sale_type').then(res => {
        this.tyingSaleTypeList = (res || []).map(item => {
          return {
            ...item,
            label: item.dictValue,
            value: item.dictValue,
          }
        })
      })
    },
    // 搭售商品
    getListTyingSaleProducts() {
      listTyingSaleProducts({orderId: this.ruleForm.id}).then(res => {
        this.refundTyingList = (res.data.data || []).map(item => {
          const detail = this.shoplist.find(d => d.id == item.id) || {}
          return {
            ...item,
            tyingRefundContent: detail.tyingRefundContent,
            tyingCheckeds: detail.tyingRefundContent && detail.tyingRefundContent.split(',')
          }
        })
        console.log(this.refundTyingList)
      })
    }
  },

  beforeDestroy() {
    if (this.detailtimer) {
      clearInterval(this.detailtimer); // 在Vue实例销毁前，清除我们的定时器
    }
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/orderdetail.scss";
.title-timeShow {
  padding-left: 150px;
  font-size: 14px;
  color: #ef4136;
  .changeColor {
    color: darkorange;
  }
  p {
    margin: 0;
    padding: 0;
    line-height: 30px;
  }
}
.warehouse {
  .el-button {
    padding: 10px;
    font-size: 12px;
  }
}
.refundcake {
  .el-checkbox {
    display: flex;
    flex-wrap: wrap;
    align-self: center;
    // margin-top: 12px;
    .el-checkbox__label {
      display: flex;
      align-self: center;
    }
  }

  .refund-order-box {
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 10px;
    display: inline-block;
  }
}
.deliveryTimeStyle {
  .el-form-item__content {
    display: flex;
    flex-direction: column;
  }
}
// 在填充数据之前隐藏
[v-cloak] {
  display: none;
}
input::-webkit-outer-spin-button,
::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
input[type="number"] {
  -moz-appearance: textfield;
}

.tying-cake {
  .tying-item {
    .el-checkbox__input {
      display: inline-flex;
      align-items: center;
    }
  }
}
.nav-menu {
  position: fixed;
  top: 80px;
  right: 80px;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, .25);
  border-radius: 2px;
  background: #fff;
}
</style>
